假设我有3个模型酒店、度假村和餐厅每个模型都具有相似的属性标题、说明、设施。。。等等…
如果我希望每个模型都有一个具有属性的位置国家、省、市、地址、纬度和经度
我应该创建位置模型,并使用有一个嵌套属性还是将位置的属性包括在这些模型中?哪种方法更可取或更好?
我认为您需要使用多态关联,因为您需要在模型上属于多个模型。你可以这样使用它:
编辑:将belongs_to :address
更改为belongs_to :locatable
,@vee对此进行了更正。
class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
end
class Hotel < ActiveRecord::Base
has_one :location, as: :locatable
end
class Resort < ActiveRecord::Base
has_one :location, as: :locatable
end
class Restaurant < ActiveRecord::Base
has_one :location, as: :locatable
end
更多详细信息:http://guides.rubyonrails.org/association_basics.html#polymorphic-协会
希望这能有所帮助。