views:

204

answers:

2

Can I sort a list of objects by a property of an associated object?

For example with the following class

class RosterSlot < ActiveRecord::Base
  belongs_to :event
  belongs_to :skill
  belongs_to :person
end

I want to do something like RosterSlot.find(:all, :order => skill.name)

which means activerecord needs to do a join and order.

Any ideas?

+3  A: 

Yes, you can use the :include option to do the join.

RosterSlot.find(:all, :include => [:skill], :order => "skills.name ASC")

The :order option takes a SQL fragment, so skills is a reference to the plural database table name.

The :include takes an array of Active Record Associations.

See http://www.railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002313&amp;name=find for more info.

Chris Saylor
That's what I was after, so obvious now. Thanks.
lyallward
+2  A: 

You can also do this within ruby by using the sort method.

RosterSlot.all.sort { |x,y| x.skill.name <=> y.skill.name }

I would personally have your db do the sorting, but this method can be useful in sorting a result set of model objects which have been returned through a method other then the ActiveRecord::Base find.

Corban Brook
You should at least make sure to do a join on the skills or you'll be hitting the database twice for each iteration of the sort.
Chuck