On Wednesday, May 11, 2011 2:17:01 PM UTC-6, danimashu wrote:
>
> 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. 
>
>
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.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to