before_destroyフック内で、どのオブジェクト(クラス)が呼び出されたかを確認する方法はありdestroyますか?
次の例では、apatientが破壊されると、それらも破壊されますappointments(これが私が望むものです)。ただし、に関連付けられているphysicianものがある場合は、を破棄することを許可したくありません。appointmentsphysician
before_destory繰り返しますが、コールバックでそのようなチェックを行う方法はありますか?そうでない場合、呼び出しの「方向」に基づいて(つまり、誰が呼び出したかに基づいて)この「破壊チェック」を実行する他の方法はありますか?
class Physician < ActiveRecord::Base
has_many :appointments, dependent: :destroy
has_many :patients, through: :appointments
end
class Patient < ActiveRecord::Base
has_many :appointments, dependent: :destroy
has_many :physicians, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :patient
belongs_to :physician
before_destroy :ensure_not_referenced_by_anything_important
private
def ensure_not_referenced_by_anything_important
unless patients.empty?
errors.add(:base, 'This physician cannot be deleted because appointments exist.')
false
end
end
end