epsilones
epsilones

Reputation: 11627

sql count filtering - rails way

Suppose I have Posts and posts' Comments. I want to filter all the Posts that have more than 10 comments. I began writing something like Posts.includes(:comments).group("post.id").count("comments.id"), to obtain a hash of posts and their counts, and I can extract the information from there, but I want some one-line straightforward way to do that

Sure I can use some pure sql syntax statements, but I want it in a pure rails way. Any idea ?

Upvotes: 0

Views: 351

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29449

Assuming the models are named in the more typical singular form of Post and Comment and have the usual association relationship, then the following should work:

Post.joins(:comments).group('posts.id').having('count(comments.id) > 10')

Upvotes: 2

Related Questions