开发者

ROR query order by association

I have a couple of rails relationships.

class Custo开发者_StackOverflow社区mer < 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}" } 


I'd use

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜