加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – has_many通过关联依赖的破坏在谁叫做破坏的条

发布时间:2020-12-16 20:53:50 所属栏目:百科 来源:网络整理
导读:有没有办法在before_destroy钩子中检查哪个对象(类)被称为destroy? 在下面的例子中,当一个病人被摧毁时,他们的约会也是如此(这就是我想要的);但是,如果有任何与该医生相关的预约,我不想让医生被销毁. 再次,有没有办法在before_destory回调中进行这样的检查
有没有办法在before_destroy钩子中检查哪个对象(类)被称为destroy?

在下面的例子中,当一个病人被摧毁时,他们的约会也是如此(这就是我想要的);但是,如果有任何与该医生相关的预约,我不想让医生被销毁.

再次,有没有办法在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

解决方法

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

请注意dependent :: restrict_with_exception.这将导致Active Record拒绝销毁任何具有相关约会记录的医生记录.

见the API docs和the association basics guide.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读