SharkLaser
SharkLaser

Reputation: 773

How to Query for Posts with 2 or more Comments

If i have the following:

class Post < ActiveRecord::Base
  has_many :comments
end


class Comment < ActiveRecord::Base
  belongs_to :post
end

How do i query for posts that have 2 or more comments? I'd like to do this in the database rather than Ruby.

Upvotes: 0

Views: 53

Answers (1)

spickermann
spickermann

Reputation: 106882

This would be extremely simply and probably faster if you set up a counter cache on this association:

Post.where('comments_count >= ?', 2)

If you do not have this counter cache, you need to do something like:

Post.select('posts.*').joins(:comments).group('posts.id').
     having('COUNT(comments.id) >= ?', 2)

Upvotes: 2

Related Questions