有没有办法在一个before_destroy
钩子中检查调用了什么对象(类)destroy
?
在下面的示例中,当 apatient
被销毁时,它们的也被销毁appointments
(这就是我想要的);physician
但是,如果有任何appointments
关联,我不想让 a被销毁physician
。
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