2014-12-05 51 views
0

简单的关联问题。 我有以下字段的选址模型: - 名称 - 地址 - 纬度 - 龙Rails - 模型belongs_to其他模型单参考

这种模式应该有很多“locationables”。

好的。我也有以下型号:

Lodging 
has_one location (location id) 

Transportation 
has_one start_location, class_name: location 
has_one end_location, class_name: location 

那么,在这种情况下,我应该在我的位置模型中有一个“belongs_to”?或者我不需要任何东西,只需将“belongs_to”放入其他模型中即可。这似乎是错误的,对吗?这似乎很简单,但我的头并没有解决它。

回答

0

要创建正确的交叉引用,您需要在类中有::belongs_to::has_and_belongs_to_many关联来启动直接引用。第一个在类中创建class_id字段(和属性读取器),第二个附加交叉引用连接表名为“class_klasses”。如果你没有礼拜堂,你可以通过绑定课程来正确设置参考,因为::has_one::has_many只是使用反向引用,而不是直接引用。所以,你需要像如下:

class Locationable < ... 
    belongs_to :location 
end 

class Lodging < ... 
    belongs_to :location 
end 

class Transportation < ... 
    belongs_to start_location, class_name: :Location 
    belongs_to end_location, class_name: :Location 
end 

或课程,以保持分贝更干净,你可以使用through键(例如)Lodging类,但只有当你在它已经有一个assotiation:

class Locationable < ... 
    belongs_to :location 
end 

class Lodging < ... 
    belongs_to :locationable 
    has_one :location, through: :locationable 
end