has_many通过关联依赖destroy条件下谁调用destroy [英] has_many through association dependent destroy under condition of who called destroy

查看:39
本文介绍了has_many通过关联依赖destroy条件下谁调用destroy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 before_destroy 钩子中检查称为 destroy 的对象(类)?

Is there a way to check, within a before_destroy hook, what object (class) called destroy?

在下面的例子中,当一个 patient 被销毁时,他们的 appointments 也会被销毁(这是我想要的);但是,如果有任何与 physician 相关的 appointments,我不想让 physician 被销毁.

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.

再说一次,有没有办法在 before_destory 回调中进行这样的检查?如果没有,有没有其他方法可以根据呼叫的方向"(即根据呼叫者)来完成这种破坏检查"?

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

推荐答案

就说:

class Physician < ActiveRecord::Base
  has_many :appointments, dependent: :restrict_with_exception
  has_many :patients, through: :appointments
end

注意dependent: :restrict_with_exception.这将导致 Active Record 拒绝销毁任何与约会记录相关联的医师记录.

Note the dependent: :restrict_with_exception. This will cause Active Record to refuse to destroy any Physician records that have associated Appointment records.

请参阅API文档协会基础指南.

这篇关于has_many通过关联依赖destroy条件下谁调用destroy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆