这是我想要实现的结构的一个例子。我只是设置一个愚蠢的例子,因此更容易解释:
假设我们有一个产品,它拥有许多不同的锤子。每个锤子都有多种属性(重量,大小,颜色等),但它们都可以钉入钉子。所以在这方面它们是可以互换的。然而,它们不能与其他产品互换,如电锯或大锤。
所以我希望能够保留所有可互换产品的清单。因此,如果没有一把锤子,我可以看到所有其他产品,我可以给客户。
由于我不知道每个产品可以有多少可互换的产品(假设有5种不同的锤子和50个螺丝刀),我不能只创建一个可互换的字段来保存这些信息。我正在考虑枚举,但是报道它们会更复杂。
这是我到目前为止所做的,但我不确定这是否是最好的解决方案(它有点迟了,我的思绪开始融化 - 如果我的自我引用表,这是一个非常简单的例子):< / p>
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
谢谢
答案 0 :(得分:0)
感谢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
希望这会对某人有所帮助。