2017-03-07 75 views
1

我正在开发一个项目,其中有许多用户,并且用户有很多帖子。我试图让帖子数超过特定阈值的用户,但我使用的查询似乎不起作用。'having clause'中的未知列:

User.where(id: user_ids) 
     .where(has_posts: true) 
     .joins(:posts) 
     .group('users.id') 
     .having('COUNT(posts.id) >= user.post_threshold') 

然而与此查询我得到Unknown column posts.id in 'having clause':

就如何解决这一问题,将不胜感激任何帮助。

+0

这样做我得到的错误'无效使用组function' – user2320239

+0

的请.to_sql'追加'这个代码的尽头并张贴在这里的结果。 – mudasobwa

+1

另外,'> = user.post_threshold'应该是'> = users.post_threshold'(注意'users'中的's')。 – mudasobwa

回答

0

您可以使用posts.*表示法,至少在Postgres中,不了解mysql。

User.where(id: user_ids) 
.where(has_posts: true) 
.joins(:posts) 
.group(:id) 
.having('COUNT(posts.*) >= users.post_threshold') 
0

你不需要having为,一个简单的where将竭诚为您服务好:

User. 
    where(id: user_ids). 
    where(has_posts: true). 
    where('COUNT(posts.id) >= users.post_threshold'). 
    joins(:posts). 
    group('users.id') 

编辑:在某些数据库中,您可能需要在select聚集,增加这个行到链:

.select('*, COUNT(posts.id)') 
+0

他不应该也需要该组。我认为他只是用它来拥有条款。 –

+0

这对我不起作用,它返回#而不是用户 – user2320239

+0

它返回了一个结果集,在Rails中称为Relation。集合中的单个条目应该是Users:尝试'result.first.class'。如果它是空的,这意味着没有用户拥有那么多帖子。 –