【发布时间】: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