Using Order on Related Tables

I have tables related as below: class Partner < ActiveRecord::Base   # :org_name, :string   # amongst other things   has_many :partner_contacts end

class PartnerContact < ActiveRecord::Base   # :partner_id, :integer, :null => false   # :name, :string   # and other stuff   belongs_to :partner end

I want to do a find on PartnerContact but order on Partner as follows: partner_contacts = PartnerContact.find(:all, :order => "partner.org_name, name"), which doesn't work.

I can't get my head around the syntax required to do this. Any help much appreciated, thanks.

I have tables related as below: class Partner < ActiveRecord::Base # :org_name, :string # amongst other things has_many :partner_contacts end

class PartnerContact < ActiveRecord::Base # :partner_id, :integer, :null => false # :name, :string # and other stuff belongs_to :partner end

I want to do a find on PartnerContact but order on Partner as follows: partner_contacts = PartnerContact.find(:all, :order => "partner.org_name, name"), which doesn't work.

I can't get my head around the syntax required to do this. Any help much appreciated, thanks.

Use the :joins option to join the tables appropriately (:joins takes
either association names or an sql fragment)

Fred

I want to do a find on PartnerContact but order on Partner as follows: partner_contacts = PartnerContact.find(:all, :order => "partner.org_name, name"), which doesn't work.

It's partner_contacts = PartnerContact.find(:all, :order => "partners.org_name, name", :include => [:partners])

the :include is needed to make that a joined query (I think :join would work too) and for "partners.org_name, name" it's important to use partners instead of partner, since this is for SQL and reflects the table name.

I want to do a find on PartnerContact but order on Partner as
follows: partner_contacts = PartnerContact.find(:all, :order => "partner.org_name, name"), which doesn't work.

It's partner_contacts = PartnerContact.find(:all, :order => "partners.org_name, name", :include => [:partners])

the :include is needed to make that a joined query (I think :join would work too)

Not only would :joins work, but it's faster than :include if you don't
actually need to eager load the associations.

Fred

Many thanks, Fred and Thorsten. For completeness, in case anybody else finds this as useful as I do, the correct syntax is

partner_contacts = PartnerContact.find(:all, :order => "partners.org_name, name", :include => [:partner])

so the include is singular but the reference in the order clause is plural.

Martin

Many thanks, Fred and Thorsten. For completeness, in case anybody else finds this as useful as I do, the correct syntax is

partner_contacts = PartnerContact.find(:all, :order => "partners.org_name, name", :include => [:partner])

Seriously, if you don't need the include, a :join is the better
solution.

Fred