我的product
模型上有一个自连接表,使用名为matches
的模型作为连接表。我想要做的是删除产品以删除相关产品但不删除。现在我正在尝试dependent: :destroy
哪个不起作用,但我知道它不是我想要的,因为我不想删除自我关联的产品。
product.rb
class Product < ApplicationRecord
...
has_many :variations, -> { order(:order) }, dependent: :destroy
has_and_belongs_to_many :categories
has_and_belongs_to_many :tags
has_many :matches
has_many :matched_products, through: :matches, dependent: :destroy
...
end
match.rb
class Match < ActiveRecord::Base
belongs_to :product
belongs_to :matched_product, class_name: 'Product', dependent: :destroy
has_many :variations, :through => :matched_product
end
答案 0 :(得分:1)
我建议您按如下方式更新模型:
<强> product.rb 强>
class Product < ApplicationRecord
...
has_many :variations, -> { order(:order) }, dependent: :destroy
has_and_belongs_to_many :categories
has_and_belongs_to_many :tags
has_many :matches, dependent: :destroy
has_many :product_matches, class_name: 'Match', foreign_key: :matched_product_id, dependent: :destroy
has_many :matched_products, through: :matches
...
end
这将确保在删除matches
时删除所有product
条记录product
是product
还是matched_product
match
记录。从dependent: :destroy
删除has_many :matched_products
会阻止删除matched_products
。
<强> match.rb 强>
class Match < ActiveRecord::Base
belongs_to :product
belongs_to :matched_product, class_name: 'Product'
has_many :variations, :through => :matched_product
end
与上述类似,从dependent: :destroy
删除belongs_to :matched_product, class_name: 'Product'
会阻止删除matched_product
。