从Rails 5自联接表中删除关联而不删除

时间:2018-03-14 21:09:18

标签: ruby-on-rails ruby-on-rails-5 ruby-on-rails-5.1

我的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

1 个答案:

答案 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条记录productproduct还是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