Has_many, belongs_to


#1

I have one table(profiles) where each row has many rows in another
table(carriers).

If I write profile.carriers I get a collection containing all carriers
that belong to the current profile.

My question is: how do I sort the collection profile.carriers? I would
like to sort it on one of the columns (found in the table carriers). Can
I override some method in the carrier model or somewhere else that adds
an “order: => ‘columnname’” statement? Or is it possible to sort the
collection after it is filled with carriers?

//Daniel


#2

Daniel wrote:

collection after it is filled with carriers?

//Daniel

As Francois told me:
find returns an Array, and Array mixes in Enumerable. See #sort_by:
http://www.ruby-doc.org/core/classes/Enumerable.html#M002092

Chris S


#3

On Mar 22, 2006, at 21:23, Chris S. wrote:

carriers?
//Daniel

As Francois told me:
find returns an Array, and Array mixes in Enumerable. See #sort_by:
http://www.ruby-doc.org/core/classes/Enumerable.html#M002092

You can always resort to sort_by, but AR allows you to specify an
order in SQL quite easily. Common idioms are

class Profile < ActiveRecord::Base
has_many :carriers, :order => ‘columname DESC’
# …
end

and

profile.carriers.find(:all, :order => 'columname DESC')

With the former you always have the collection ordered by default.
The latter one orders the collection locally.

Note that find() in the latter case is not the regular
Enumerable#find. has_many brings an attribute that behaves quite
naturally like a regular collection, but find() is different is a
custom method.

– fxn