【发布时间】:2012-04-19 20:36:36
【问题描述】:
有没有办法在 before_destroy 挂钩中检查名为 destroy 的对象(类)?
在下面的例子中,当一个patient被销毁时,他们的appointments也被销毁(这是我想要的);但是,如果有任何 appointments 与 physician 关联,我不想让 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
【问题讨论】:
标签: ruby-on-rails associations destroy