【问题标题】:How to setup the associations for an "Options" model?如何为“选项”模型设置关联?
【发布时间】:2012-06-05 12:13:33
【问题描述】:

如果模型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 模型,该模型包含模型特定选项类型,例如,如果庄园有后院、游泳池、网球场或价格有交易、折扣或买一送一。这会通过多态关联来完成吗? 我这样做是为了不必为每个模型创建一个选项模型,并且可以只为我想要添加的所有新选项创建一个模型。那么这是解决这个问题的正确方法吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3.1 rails-activerecord


    【解决方案1】:

    如果您使用多态选项模型,则对象所属的每个类/记录的字段都是相同的。我认为这不是您想要的,因为交易没有游泳池,而庄园也不是买一送一的(我希望!)。

    我会考虑使用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
    

    【讨论】:

    • 哈哈@买一送一的庄园。如果我使用的是 Rails 3.1,我是否必须创建 Price OptionsEstate Options 才能做我想做的事情?
    • 好吧,您仍然可以对所有人使用多态选项模型,但您必须将所有选项放在那里并为您的视图添加更多逻辑(不推荐)。或者您可以将选项直接放入模型/表中,但如果您需要任意选项,则不建议这样做,否则它们会经常更改(大量迁移)。
    猜你喜欢
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多