[Model Scopes] How to count a nested

Hello, I have a Post that has_many Comments. I have the next scopes:

scope :valid, where('created_at >= ?', 2.months.ago)
scope :expired, where('created_at < ?', 2.months.ago)

Now, I would have a scope named :commented that return all the Post
that have more than 0 Comments but I don't know how do it clearly. A
solution is have a counter num_comments column in Post, but I don't
know if that is the best practice.

Thanks for your advices. Bye.

Daniel

It is common for one record type has_many another to “cache” the count of just how many it has. At least it’s common enough that rails can maintain this counter column for you automagically:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to

See the :counter_cache option of the #belongs_to method. With this, you might have:

class Comment
belongs_to :post, :counter_cache => true
end
class Post
has_many :comments
end

The above example just requires that you have a column in your posts table named “comments_count”. You can use another name, such as your proposed “num_comments” by instead using:

belongs_to :post, :counter_cache => :num_comments

Anyhow, if you do this then rails will keep this count column up-to-date. Then you can easily create your desired named scope.

class Comment
belongs_to :post, :counter_cache => true
end
class Post
has_many :comments
end

Thanks so much Kendall, nice solution.