9

通常の では、親レコードが削除されたときに関連付けを削除するhas_manyオプションがあります。:dependent => :destroyではhas_many :through、子レコードに関連付けられた他の親が存在する可能性があるため、:dependent => :destroy影響はありません。

子レコードが最後の HMT 関連付けから孤立した後、子レコードが確実に削除されるようにするにはどうすればよいですか?

4

2 に答える 2

13

私が見つけた解決策は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
于 2009-04-19T23:33:41.717 に答える
1

結合モデルで、「belongs_to :model、dependent: :destroy」を使用します

たとえば、医師が破棄された後に患者を破棄したい場合、医師は予約を介して多くの患者を持っています

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
于 2012-09-09T23:35:52.450 に答える