通过定期has_many,有:dependent => :destroy的删除协会当父记录被删除的选项。随着has_many :through,可能有相关子记录的其他家长,所以:dependent => :destroy没有任何效果。

您如何确保他们从过去的HMT协会孤儿后子记录被删除?

有帮助吗?

解决方案

我已发现该溶液似乎是一个after_destroy回调,如这样的:

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

其他提示

在该连接模型中,使用 “belongs_to的:模型,取决于:消灭”

例如,如果要摧毁病人一旦他们的医生被破坏,医生的has_many患者虽然约会

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top