如果模型Store
,Product
,User
和Price
具有以下关联
class User < ActiveRecord::Base
has_many :products
has_many :stores
has_many :prices
end
class Store < ActiveRecord::Base
belongs_to :user
has_many :prices
end
class Product < ActiveRecord::Base
belongs_to :user
has_many :prices
end
class Price < ActiveRecord::Base
belongs_to :user
belongs_to :product
belongs_to :store
end
class Estate < ActiveRecord::Base
belongs_to :user
end
并且想要创建一个Option
模型,其中包含模型特定选项类型,如果Estate有后院,游泳池,网球场或价格有交易,折扣或买一送一自由。这是通过多态关联来完成的吗?
我这样做是因为我不必为每个模型创建一个Option模型,并且可以为我想要添加的所有新选项创建一个模型。那么这是正确的方法吗?
答案 0 :(得分:2)
如果使用多态选项模型,则对象所属的每个类/记录的字段都相同。我不认为这是你想要的,因为一笔交易没有游泳池而且庄园不是买一送一(我希望!)。
我会考虑使用Rails 3.2 and the ActiveRecord::Store feature。有了这个,只需在模型中添加一个文本列(称之为“选项”),然后就可以定义所需的所有选项。
class Estate < ActiveRecord::Base
belongs_to :user
store :options, accessors: [ :backyard, :pool, :tennis, :butler, :wine_cellar ]
end
estate = Estate.new
estate.pool = true
estate.options[:number_of_sharks] = 3 # Attributes not defined as accessors work too