has_many通过关联依赖的破坏在谁叫毁灭的条件下

use*_*833 6 ruby-on-rails associations destroy

有没有办法在before_destroy钩子内检查哪个对象(类)调用destroy

在下面的例子中,当a patient被销毁时,他们也是appointments(这就是我想要的); 但是,physician如果有任何appointments关联,我不想允许销毁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
Run Code Online (Sandbox Code Playgroud)

Ans*_*nsh 19

请注意,dependent: :destroyhas_many :through关系上只删除关联而不删除关联的记录(即连接记录将被删除,但关联的记录将不会删除).因此,如果你删除patient它只会删除appointment而不是删除physician.阅读API文档中的详细说明.

我已粘贴以下相关段落.

什么被删除?

这里有一个潜在的缺陷:has_and_belongs_to_manyhas_many :through协会在连接表,以及相关记录的记录.那么当我们调用其中一种删除方法时,应该删除哪些内容?

答案是假设对关联的删除是关于删除所有者和关联对象之间的链接,而不是必然是关联对象本身.因此,使用has_and_belongs_to_manyhas_many :through,将删除连接记录,但相关记录将不会删除.

如果你想一想,这是有道理的:如果你打电话,post.tags.delete(Tag.find_by_name('food'))你会希望food标签与标签取消链接post,而不是标签本身从数据库中删除.


Mic*_*ade 11

说啊:

class Physician < ActiveRecord::Base
  has_many :appointments, dependent: :restrict_with_exception
  has_many :patients, through: :appointments
end
Run Code Online (Sandbox Code Playgroud)

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

请参阅API文档关联基础指南.