Charles Smith
Charles Smith

Reputation: 3289

Remove association from Rails 5 self join table without deleting

I have a self join table on my product model using a model called matches as the join table. What I would like to do is when deleting a product to have the associated product removed but not deleted. Right now I am trying dependent: :destroy which doesn't work, but I know its not what I want because I don't want to delete the self associated product.

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

Upvotes: 0

Views: 1490

Answers (1)

jvillian
jvillian

Reputation: 20263

I suggest you update your models as follows:

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

This will ensure that all matches records are deleted when deleting a product whether the product is a product or matched_product in the match record. Removing dependent: :destroy from has_many :matched_products will prevent deletion of the, well, 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

Similar to above, removing dependent: :destroy from belongs_to :matched_product, class_name: 'Product' will prevent deletion of the matched_product.

Upvotes: 1

Related Questions