Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroy associations after the last has_many :through record is deleted

With a regular has_many, there's the option of :dependent => :destroy to delete the associations when the parent record is deleted. With has_many :through, there might be other parents associated to the child records, so :dependent => :destroy doesn't have any effect.

How do you ensure child records are deleted after they are orphaned from the last HMT association?

like image 937
Andrew Vit Avatar asked Apr 19 '09 23:04

Andrew Vit


2 Answers

The solution I have found seems to be an after_destroy callback, such as this:

class Parent < ActiveRecord::Base
  has_many :children, :through => :parentage
  after_destroy :destroy_orphaned_children

  private

  def destroy_orphaned_children
    children.each do |child|
      child.destroy if child.parents.empty?
    end
  end

end
like image 63
Andrew Vit Avatar answered Oct 20 '22 04:10

Andrew Vit


On the join model, use "belongs_to :model, dependent: :destroy"

for example, if you want to destroy a patient once their doctor is destroyed, and doctor has_many patients though appointments

Class Appointment
  belongs_to :doctor
  belongs_to :patient, dependent: :destroy

Class Doctor
  has_many :appointments, dependent: :destroy
  has_many :patients, through: :appointments

Class Patient
  has_many :appointments
  has_many :doctors, through: :appointments
like image 36
suga_shane Avatar answered Oct 20 '22 05:10

suga_shane