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

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and 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

Hope that's useful...

This topic is locked and can not be replied to.