Filter by number of children using Rails 3

I would like to select posts containing one or more comments using Rails 3 and one query.

I am 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 was looking for this and similar approaches, group, etc., no luck. Any help would be appreciated.

+4
source share
1 answer

I am sure that you might have guessed this, but I believe that what you are looking for is a relationship with (: conditions), Jose.

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

I have not tested this code, so please take it with salt, but you can probably start from this point.

+1
source

All Articles