Filter by count of children using Rails 3

允我心安 提交于 2019-12-23 13:09:36

问题


I'd like to select posts that have one or more comments using Rails 3 and a single query.

I'm trying something like this:

Post.includes(:comments).where('count(comments.id)>0')

However I get this error:

ActiveRecord::StatementInvalid: PGError: ERROR:  aggregates not allowed in WHERE clause

I've googled this and similar approaches, group by, etc with no luck. Any help will be appreciated.


回答1:


I'm sure you may have figured this out by now, but I believe what you're looking for is the having(:conditions) relationship, Jose.

Post.includes(:comments).having(:conditions => "count(comments.id) > 0")

I haven't tested that code so please take it with a grain of salt, but you should definitely be able to jump start from there.



来源:https://stackoverflow.com/questions/3980568/filter-by-count-of-children-using-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!