Remove association from Rails 5 self join table 不删除

Remove association from Rails 5 self join table without deleting

我在我的 product 模型上有一个自连接 table,使用名为 matches 的模型作为连接 table。我想做的是在删除产品时删除相关产品但不删除。现在我正在尝试 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

我建议您按如下方式更新您的模型:

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

这将确保在删除 product 时删除所有 matches 记录,无论 productproduct 还是 matched_product 17=]记录。从 has_many :matched_products 中删除 dependent: :destroy 将防止删除 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

与上面类似,从 belongs_to :matched_product, class_name: 'Product' 中删除 dependent: :destroy 将防止删除 matched_product