2009-08-21 100 views
1

我想要做的是在between..Here的抽象使用两个中介模型加入一个模型到另一个:如何在两个模型之间创建has_many关系,其中有几个模型? (Ruby on Rails的ActiveRecord的)

 
Country has_many Companies 
Company has_many Buildings, Company belongs_to Country 
Building has_many Rooms, Building belongs_to Company 
Room belongs_to Building 

我希望能够做Country.first .rooms,所以我想作为全国模型应该是简单的:

 
class Country - ActiveRecord::Base 
    has_many :companies 
    has_many :buildings, :through=>:companies 
    has_many :rooms, :through=>:buildings 
end 

然而,这种尝试生成SQL这样的: SELECT * FROM rooms INNER JOIN buildings ON rooms .building_id = building .ID WHERE(( building.country_id = 1))

显然,building.country_id不存在......我如何解决这个问题?

+0

什么是您的Rails(特别是ActiveRecord)版本? – steel 2016-04-24 02:04:40

回答

1

建立在关联方法不会帮助你在这里。你需要明确建立查询使用联接:

class Country - ActiveRecord::Base 

    has_many :companies 
    has_many :buildings, :through=>:companies 

    def rooms 
     Room.all :joins => { :building => { :company => :country } }, :conditions => { "countries.id" => id } 
    end 

end 

这将需要进行设置在建筑物的belongs_to的协会和公司模型

+0

因此,我得到一个错误: ActiveRecord :: ConfigurationError:找不到名为'country'的关联;也许你拼错了吗? 我猜这是因为“建筑”,这是一个从国家中删除的模型(它们与“公司”明确属于一个国家相关联)只与国家隐含相关。 – 2009-08-21 16:08:56

+0

你是正确的我错过了 – derfred 2009-08-21 17:26:18

0

这Rails的3.1后可能。下面的代码适用于我。在每个级别指定has_many很重要。

class Country 
    has_many :companies 
    has_many :buildings, through: :companies 
    has_many :rooms, through: buildings 
end 

class Company 
    has_many :buildings 
end 

class Building 
    has_many :rooms 
end 

class Room 
end 
相关问题