Filter by count of children using Rails 3
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 w开发者_StackOverflow中文版ith no luck. Any help will be appreciated.
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.
精彩评论