我正在开发一个具有“产品”模型的 Rails 应用程序。我希望能够将产品相互关联起来。示例:产品 1 与产品 2、产品 3 相关,反之亦然。我将如何在 Rails 中完成此操作?我在考虑一个连接表,但由于我使用同一个表作为关系点,我不确定它是如何工作的。
最佳答案
未经测试和凭内存,我想你会想要这样的东西:
class ProductLink < ActiveRecord::Base
belongs_to :parent_product, :class_name => 'Product'
belongs_to :child_product, :class_name => 'Product'
end
class Product < ActiveRecord::Base
has_many :parent_links, :class_name => 'ProductLink', :foreign_key => :parent_product_id
has_many :child_links, :class_name => 'ProductLink', :foreign_key => :child_product_id
end
ProductLink(或您选择的任何称呼)随后将能够包含一个或多个描述关系的附加字段。
你可以让它与 has_and_belongs_to_many 一起工作,虽然我猜这需要一个“products_products”表,这可能有点压力。
关于ruby-on-rails - 同一张表的多对多关系(Ruby on Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/987154/