mjankowski@unicorngroomers.com
2006-Jun-07 08:55 UTC
[Rails] Calling find on AR class, order by association count?
I suspect that this is going to wind up trivial and I''m going to slap myself in the head... Suppose I have User and Comment AR classes. User has_many :comments, Comment belongs_to :user I want to do a User.find, which returns User objects in order of which user has the most comments. I suspect that this involves renaming the COUNT(*) results of a sub-select so that I can order by them. Answers, links to answers? -Matt
Rodney Ramdas
2006-Jun-07 10:14 UTC
[Rails] Calling find on AR class, order by association count?
hi Matt, have a look at ActiveRecord#calculations in the api basically something like this: topspammers = Comment.count(:all, :group => ''user_id'' , :order => ''count_all desc'') gives you a nice OrderedHash with the user_id as key and the number of comments belonging to that user as the value hth On 6/6/06, mjankowski@unicorngroomers.com <mjankowski@unicorngroomers.com> wrote:> I suspect that this is going to wind up trivial and I''m going to slap > myself in the head... > > Suppose I have User and Comment AR classes. > > User has_many :comments, Comment belongs_to :user > > I want to do a User.find, which returns User objects in order of which > user has the most comments. I suspect that this involves renaming the > COUNT(*) results of a sub-select so that I can order by them. > > Answers, links to answers? > > -Matt > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >-- Rodney http://www.pinupgeek.com http://www.dutchrailers.org