【问题标题】:What would be a good way to model interchangable items in Rails 3?在 Rails 3 中建模可互换项目的好方法是什么?
【发布时间】:2011-11-01 01:24:35
【问题描述】:

这是我试图实现的结构示例。我只是设置一个愚蠢的例子,以便更容易解释:

假设我们有一个产品,其中包含一堆不同的锤子。每个锤子都有多个属性(重量、大小、颜色等),但它们都可以钉入钉子。所以在这方面它们是可以互换的。但是,它们不能与其他产品互换,例如电锯或大锤。

所以我希望能够保留所有可互换产品的列表。因此,如果没有一把锤子,我可以看到我可以提供给客户的所有其他产品的 ID。

由于我不知道每个产品可以有多少可互换的产品(假设有 5 种不同的锤子和 50 把螺丝刀),我不能只创建一个可互换的字段来保存此信息。我在考虑枚举,但在它们上运行报告更复杂。

这是我目前所拥有的,但我不确定这是否是最好的解决方案(有点晚了,我的思绪开始融化 - 如果我的自引用表,这是一个非常简化的示例):

class Product < ActiveRecord::Base

  has_many :interchangable_products, :dependent => :destroy
end


class InterchangableProduct < ActiveRecord::Base
  belongs_to :product, :class => "Product", :foreign_key => :product_id


  belongs_to :interchangable_with, :class_name => "InterchangableProduct", :foreign_key => :interchangable_with_id
  has_many   :interchangables, :class_name => "InterchangableProduct",  :inverse_of => :interchangable_with, :foreign_key => :interchangable_with_id

  validates :product_id, :presence => true, :uniqueness => [:scope => :interchangable_with_id]
end

谢谢

【问题讨论】:

  • 似乎创建一个“产品”类型系统比单独链接每个可能的关系更实用?此外,似乎可互换产品只是产品,因此has_many:through 可能是更清洁的模型。
  • 正如我所说,我一直在思考这个问题太久了。我应该将 InterchangableProduct 视为 InterchangableProductRelationship。再次在我的脑海中命名错误......谢谢你,戴夫!

标签: ruby-on-rails activerecord foreign-key-relationship has-many belongs-to


【解决方案1】:

感谢 Dave Newton 的评论,我得到了一个看起来像这样的解决方案:

class InterchangeableProductRelationship < ActiveRecord::Base
  belongs_to :product, :class_name => "Product", :foreign_key => "product_id"
  belongs_to :interchangeable_product, :class_name => "Product", :foreign_key => "interchangeable_product_id"

  validates :product_id, :presence => true, :uniqueness => [:scope => :interchangeable_product_id]
end


class Product < ActiveRecord::Base
  has_many :relations_to, :foreign_key => 'product_id', :class_name => "InterchangeableProductRelationship"
  has_many :relations_from, :foreign_key => 'interchangeable_product_id', :class_name => "InterchangeableProductRelationship"  
  has_many :linked_to, :through => :relations_to, :source => :interchangeable_product
  has_many :linked_from, :through => :relations_from, :source => :product


  def interchanges_with
    self.linked_to | self.linked_from
  end 
end

希望这对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2011-12-05
    • 1970-01-01
    • 2011-08-09
    • 2011-04-26
    • 2011-04-13
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多