Sorting by a field of an associated class

I feel like i should know this but i’ve got the lurgy and am feeling a
bit dumb…

If a User belongs_to a Company, how do i find a list of users, ordered
by user.company.name?

thanks
max

You can write a method like following in the user.rb

def <=>(user)
self.company.name <=> user.company.name
end

and use the sort method of array to sort the users. for example,
users.sort

If you are using user.find method then use the following symbols in the
find method :include => ‘company’ :order => ‘company.name’

Ayyanar Aswathaman wrote:

If you are using user.find method then use the following symbols in the
find method :include => ‘company’ :order => ‘company.name’

nice one, thanks!

Max W. wrote:

Ayyanar Aswathaman wrote:

If you are using user.find method then use the following symbols in the
find method :include => ‘company’ :order => ‘company.name’

nice one, thanks!

Actually to get this to work i had to change the value of :order to
:order => ‘companies.name’, ie to match the name of the db table.

Max :

Actually to get this to work i had to change the value of :order to
:order => ‘companies.name’, ie to match the name of the db table.

You can use :order => “#{Company.table_name}.name”
to avoid thinking about the real (eventually legacy) name of the db
table.

– Jean-François.

Jean-François Trân wrote:

Max :

Actually to get this to work i had to change the value of :order to
:order => ‘companies.name’, ie to match the name of the db table.

You can use :order => “#{Company.table_name}.name”
to avoid thinking about the real (eventually legacy) name of the db
table.

– Jean-Fran�ois.

Thanks - that will be useful in few situations actually :slight_smile: