2013-02-08 63 views
0

毫無疑問,這是一個簡單的問題,但我不能抱怨的Rails 3.2的has_many:通過如何讓只有在相關的模型加入模型

class Service < ActiveRecord::Base 
    has_many :offers 
    has_many :offices,:through=> :offers 
    has_many :addresses,:through => :offices 
    has_many :locations,:through => :adreesses,:include => :offices 
end 

class Offer < ActiveRecord::Base 
    belongs_to :service 
    belongs_to :office 
end 

class Office < ActiveRecord::Base 
    has_many :offers 
    has_many :services,:through => :offers 
    has_one :adreess 
end 

class Address 
    belongs_to :office 
    belongs_to :location 
end 

class Location < ActiveRecord::Base 
    has_many :addressess 
    has_many :offices,:through => :addresses,:uniq=>true 
end 

我想顯示,例如:

Service name: Entrega especial 

    Location name: Distrito Capital 
    Offices: 
     Name: San Martin 

    Location name: Carabobo 
    Offices: 
     Name: San diego 

但是當我這樣做

service = Service.where(:nombre=> "Entrega especial") 
locations = service.locations 

locations.offices.each do |o| 
    puts o.nombre # only I want the offices with that service 
in that Location, no all offices in that location 
end 

我不知道如何只顯示關係辦公室,而不是所有的辦公室在該位置,即使沒有該服務的報價,在snoth方式,無需使用一個assosiation擴展和管理proxy_xxx對象

+0

是它也許可以重構你的問題?我發現很難理解你真正想知道或實現的內容。 – 2013-02-08 15:02:53

+0

我編輯部分我想要顯示的內容,我想在每個位置設置組辦公室,但只顯示在此位置提供特定服務的辦事處 – Orlando 2013-02-08 16:47:38

回答

0

,也許這是最好要經過辦事處協會

@offices = service.offices.includes(:location) 

@offices.group_by(&:location).each do |location, offices_by_location| 
    puts "Location: #{location}" 
    offices_by_location.each do |office| 
    puts "Office: #{office}" 
    end 
end 
+0

uhmmm,好的,有趣的,我會試試這種方式,謝謝,我一直在尋求其他方式來做到這一點 – Orlando 2013-02-08 16:52:48

相關問題