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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – has_many通过关联依赖的破坏在谁叫做破坏的条件下前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法在before_destroy钩子中检查哪个对象(类)被称为destroy?

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

再次,有没有办法在before_destory回调中进行这样的检查?如果没有,是否还有其他方法可以根据通话的“方向”(即根据谁打电话)完成“破坏检查”?

  1. class Physician < ActiveRecord::Base
  2. has_many :appointments,dependent: :destroy
  3. has_many :patients,through: :appointments
  4. end
  5.  
  6.  
  7. class Patient < ActiveRecord::Base
  8. has_many :appointments,dependent: :destroy
  9. has_many :physicians,through: :appointments
  10. end
  11.  
  12.  
  13. class Appointment < ActiveRecord::Base
  14. belongs_to :patient
  15. belongs_to :physician
  16.  
  17. before_destroy :ensure_not_referenced_by_anything_important
  18.  
  19. private
  20.  
  21. def ensure_not_referenced_by_anything_important
  22. unless patients.empty?
  23. errors.add(:base,'This physician cannot be deleted because appointments exist.')
  24. false
  25. end
  26. end
  27. end

解决方法

说啊:
  1. class Physician < ActiveRecord::Base
  2. has_many :appointments,dependent: :restrict_with_exception
  3. has_many :patients,through: :appointments
  4. end

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

the API docsthe association basics guide.

猜你在找的Ruby相关文章