开发者

Filter by count of children using Rails 3

开发者 https://www.devze.com 2023-01-21 04:04 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消