Alex Rivera | Logout

How to sort Rails AR.find by number of objects in a has_many relationship

Asked 2009-06-11T13:24:38.047
10

How can I write an AR find query to have the results ordered by the number of records in a has_many association?

class User < ActiveRecord::Base
  has_many :photos
end

I want to do something like...

User.find(:all, :order => photos.count)

I realize my find is not valid code. Say I have the following data.

User 1, which has 3 photos 
User 2, which has 5 photos 
User 3, which has 2 photos 

I want my find to bring me back the users in the order of...

User 2, 
User 1, 
User 3 

based on the count of of the users photos

Edit
Report

1 Answer

19

The easiest way to achieve this is probably to add a counter cache to that model and then sort by that column.

class Photo < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
end

And be sure to add a column to your users table called photos_count.

Then you will be able to...

User.find(:all, :order => 'photos_count')
answered 2009-06-11T13:39:27.590

Your Answer