最後にhas_many後の関連付けを破棄:レコードが削除されて
-
12-09-2019 - |
質問
定期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
所属していません StackOverflow