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.

On 14 Aug 2008, at 11:45, MJohnH wrote:

: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.

On 14 Aug 2008, at 11:53, Thorsten Müller wrote:

“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

On Aug 14, 11:57 am, Frederick C. [email protected]

On 14 Aug 2008, at 12:07, Martin H. wrote:

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs