views:

503

answers:

1

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?

+5  A: 

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
Andrew Vit