Ruby on rails 在Rails 3中建模可交换项的好方法是什么?

Ruby on rails 在Rails 3中建模可交换项的好方法是什么?,ruby-on-rails,activerecord,foreign-key-relationship,has-many,belongs-to,Ruby On Rails,Activerecord,Foreign Key Relationship,Has Many,Belongs To,下面是我试图实现的结构示例。我将设置一个愚蠢的示例,以便更容易解释: 比如说,我们有一个产品,它可以装一堆不同的锤子。每个锤子都有多个属性(重量、大小、颜色等),但它们都可以将钉子锤入。因此,在这方面,它们是可互换的。但是,它们不能与其他产品互换,如链锯或大锤 所以我希望能够保留一份所有可互换产品的清单。因此,如果一个锤子不可用,我可以看到我可以提供给客户的所有其他产品 因为我不知道每个产品可以有多少个可互换的产品,比如说有5个不同的锤子和50个螺丝刀,我不能创建一个可互换的字段来保存这些信息。

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

比如说,我们有一个产品,它可以装一堆不同的锤子。每个锤子都有多个属性(重量、大小、颜色等),但它们都可以将钉子锤入。因此,在这方面,它们是可互换的。但是,它们不能与其他产品互换,如链锯或大锤

所以我希望能够保留一份所有可互换产品的清单。因此,如果一个锤子不可用,我可以看到我可以提供给客户的所有其他产品

因为我不知道每个产品可以有多少个可互换的产品,比如说有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

谢谢你

感谢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

希望这会对某些人有所帮助。

似乎创建产品类型系统比单独链接所有可能的关系更实际?而且,似乎可互换的产品只是产品,所以a有很多:through可能是一个更干净的型号。正如我说的,我已经绞尽脑汁想这个问题太久了。我应该把InterchangableProduct看作InterchangableProductRelationship。我脑子里又在胡思乱想了。。。谢谢你,戴夫!!