lyallward
lyallward

Reputation: 415

sort list of objects by property on associated object

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?

Upvotes: 3

Views: 2296

Answers (2)

Corban Brook
Corban Brook

Reputation: 21378

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.

Upvotes: 3

Chris Saylor
Chris Saylor

Reputation: 166

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&name=find for more info.

Upvotes: 4

Related Questions