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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With