2012-06-05 22 views
0

如果曾经有过的车型StoreProductUserPrice与以下关联如何设置“选项”模型的关联?

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模型,用之类的东西保持模型的特定选项类型,如果一个村有一个后院,游泳池,网球场或价格有优惠,折扣或买一送一。这是通过多态关联来完成的吗? 我这样做,所以我不必为每个模型创建一个选项模型,并且可以为我想要添加的所有新选项创建一个模型。那么这是否是正确的方法呢?

回答

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 
+0

Lol @买一买一免费房地产。如果我使用的是Rails 3.1,那么我需要做一个'Price Options'和'Estate Options'来做我想做的事吗? – LearningRoR

+1

那么,你仍然可以为所有人使用多态选项模型,但是你必须将所有选项放在那里,并向视图添加更多逻辑(不推荐)。或者您可以直接将选项放入模型/表格中,但如果您需要任意选项,或者它们会经常更改(大量迁移),则不推荐使用这些选项。 – Callmeed

相关问题