Ruby on rails 如何在两个模型之间创建多个关系,在多个模型之间创建多个关系?(RubyonRailsActiveRecord)
我想做的是使用两个中间模型将一个模型连接到另一个模型。以下是抽象: 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,因此我认为Country模型将非常简单:Ruby on rails 如何在两个模型之间创建多个关系,在多个模型之间创建多个关系?(RubyonRailsActiveRecord),ruby-on-rails,activerecord,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 这个国家有许多公司 公司有许多建筑物,公司属于国家 大楼有许多房间,大楼属于公司 这个房间属于这幢大楼 我希望能
class Country < ActiveRecord::Base
has_many :companies
has_many :buildings, :through=>:companies
has_many :rooms, :through=>:buildings
end
class Country:公司
有许多:房间,:到=>:建筑物
结束
但是,这会尝试生成类似以下内容的SQL:
从房间
内部连接建筑
上的房间
中选择*建筑id=建筑
.id,其中(建筑
国家/地区id=1))
显然,building.country\u id不存在。我该如何解决这个问题?内置的关联方法在这里对您没有帮助。您需要使用联接显式生成查询:
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
这将要求在建筑和公司模型上设置“属于”关联内置关联方法在这里对您没有帮助。您需要使用联接显式生成查询:
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
这将要求在建筑物和公司模型上设置“归属”关联尝试使用尝试使用这在Rails 3.1之后是可能的。下面的代码适用于我。重要的是要指定
在每个级别上都有许多
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
这在Rails 3.1之后是可能的。下面的代码适用于我。重要的是要指定
在每个级别上都有许多
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
这样,我得到了一个错误:ActiveRecord::ConfigurationError:找不到名为“country”的关联;也许你拼错了?我猜这是因为“building”是从国家/地区删除的一个模型(它们由“Company”关联,该公司明确属于一个国家/地区),它只与国家/地区隐式关联;也许你拼错了?我猜这是因为“building”,这是一个从国家删除的模型(它们由“Company”关联,它明确属于一个国家)只与国家隐含相关。你的Rails(特别是ActiveRecord)版本是什么?你的Rails(特别是ActiveRecord)版本是什么?