Order Rails Find result by associated model

February 4, 2008

 
No Gravatar

Sorting information properly allows users to navigate your application quickly, and more effectively. There’s nothing more annoying than unsorted, unusable data! As Rails users, most of you have associated models. Have you ever wondered how to sort by the associated model using the find method?

Like everything in Rails, once you know, the solution is simple. By passing the :include argument in the find method you can include the associated model, and then automatically order by the column of your choosing!

1
2
3
4
5
6
7
8
9
10
11
12
# the Profile model
class Profile > ActiveRecord::Base
 belongs_to :user
end
 
# the User model
class User > ActiveRecord::Base
 has_one :profile
end
 
# my controller
@users = User.find(:all, :include => :profile, :order => "profiles.last_name")
blog comments powered by Disqus