Topic: :order => by a has_many relationship?

Hey, this is probably a simple question that has been answered before but I can't seem to find a solution to it. I have two objects, lets call them Item and Owner. The relationships are:

item belongs_to owner

owner has_many item

I have foreign keys set up, everything works etc.

What if I want to sort my items, but owner.full name? I can't use :order => 'owner.full_name' because that is throwing that into raw MySQL, which obviously doesn't take Rails relationships.

I see there is an order command that you can specify in the model when you set the relationship. I have not tinkered with it because I have the following issue with it: If I set this to order => full_name, what happens if later on I want to sort by order => age?

I'm probably missing something crucial here along the I?


Re: :order => by a has_many relationship?

No problem to define :order in your relationship, if you do later on Owner.find(:all, :order => :age), your :name order will be overruled.
But what's the name of your table, owner or owners?
orders is rails default and in that case you should put :order => 'owners.full_name' (or :order => :full_name)

Does this answer your question ?


Re: :order => by a has_many relationship?

Thank you! I wasn't adding the 's' to the model name, which is why it wasn't working. I appreciate it.

Re: :order => by a has_many relationship?

OK after playing with it, this works, but in my find statement you must have

:include => [:owner]

Just throwing it out there in case somebody searches this.