通过的has_many协会依赖的所谓谁破坏条件下摧毁 [英] has_many through association dependent destroy under condition of who called destroy
问题描述
有没有一种方法来检查时, before_destroy
挂钩,什么对象(类)呼吁在摧毁
<? / p>
在下面的例子中,当耐心
被破坏,所以他们的约会
(这就是我想要的);但是,我不想让医师
如果有任何约会被摧毁
与之关联医师
。
此外,有没有办法做到在 before_destory
回调这样的检查?如果没有,是否有任何其他的方式来完成的基础上的呼叫(即根据谁的称呼)的方向这种毁灭检查?
类医师LT; ActiveRecord的::基地
的has_many:约会,取决于:摧毁
的has_many:患者,通过:任命
结束
类病人LT; ActiveRecord的::基地
的has_many:约会,取决于:摧毁
的has_many:医生通过:任命
结束
任命类LT&; ActiveRecord的::基地
belongs_to的:病人
belongs_to的:医生 before_destroy:ensure_not_referenced_by_anything_important 私人的 高清ensure_not_referenced_by_anything_important
除非patients.empty?
errors.add(:基地,这医生不能因为存在约会删除。')
假
结束
结束
结束
只是说:
类医师LT; ActiveRecord的::基地
的has_many:约会,取决于:restrict_with_exception
的has_many:患者,通过:任命
结束
请注意在相关:restrict_with_exception
。这将导致活动记录拒绝销毁有关联的约会记录的医生记录。
Is there a way to check, within a before_destroy
hook, what object (class) called destroy
?
In the following example, when a patient
is destroyed, so are their appointments
(which is what I want); however I don't want to allow a physician
to be destroyed if there are any appointments
associated with that physician
.
Again, is there a way to do such a check in the before_destory
callback? If not, is there any other way to accomplish this "destruction check" based on the "direction" of the call (i.e. based on who called)?
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
Just say:
class Physician < ActiveRecord::Base
has_many :appointments, dependent: :restrict_with_exception
has_many :patients, through: :appointments
end
Note the dependent: :restrict_with_exception
. This will cause Active Record to refuse to destroy any Physician records that have associated Appointment records.
See the API docs and the association basics guide.
这篇关于通过的has_many协会依赖的所谓谁破坏条件下摧毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!