Forum: Ruby on Rails RE: Order By Number of Comments

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Andrew Cherry (Guest)
on 2006-04-03 19:52
(Received via mailing list)
One other thing you could do is add an auto-populating field to the
parent in the relationship. So, say I have a post model, which has_many
:comments. Using a magic field of comments_count, this will be
auto-updated when comments are added or removed from the post. So, I
could get the list in the order you want, by simply doing...

.find(:all, :order_by => 'comments_count DESC', :conditions =>
['comments_count > x'])

And then I can forget about joins etc... Handy magic field name! (Saves
doing a count - note that doing .count on comments still uses a count
statement).

Hope that's useful...

Andrew
This topic is locked and can not be replied to.