views:

14

answers:

2

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.

A: 

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}" } 
jpemberthy
A: 

I'd use

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