简体   繁体   中英

ROR query order by association

I have a couple of rails relationships.

class Customer < ActiveRecord::Base
 has_many :sites
end

class Site < ActiveRecord::Base
 belongs_to :Customer
end

I want to be able to get a list of sites ordered by the long-name field of the customer and then the long-name field of the site, I want to use the list in a select element on a page, where the individual options will look like this.

Ordered first by the Customer, and then the Sites for that Customer. I do not want to see Customers that have no sites.

  • Ball State University - Student Union Building
  • Boise State University - Administration
  • Boise State University - Student Union Building

I cannot figure out how to build my Site.find statement.

I'd go with somethig like this:

@sites = Site.find(:all, :joins => :customer, :order => "customers.long_name, sites.long_name")

And then,

@sites.each { |s| "#{s.customer.long_name} - #{s.long_name}" } 

我会用

Site.all(:include => :customer, :order => "customers.name, sites.name")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM