has_many通过关联依赖的破坏在谁叫毁灭的条件下
有没有办法在before_destroy
钩子中检查哪个对象(类)被称为destroy
?
在下面的例子中,当一个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
说啊:
class Physician < ActiveRecord::Base has_many :appointments, dependent: :restrict_with_exception has_many :patients, through: :appointments end
请注意dependent: :restrict_with_exception
。 这将导致Active Record拒绝销毁任何具有相关约会记录的医生记录。
请参阅API文档和关联基础指南 。
请注意, dependent: :destroy
on has_many :through
关系只删除关联而不删除关联记录(即连接记录将被删除,但相关记录将不会删除 )。 因此,如果您删除patient
,它将只删除appointment
而不是physician
。 阅读API文档中的详细说明。
我已粘贴以下相关段落。
什么被删除?
这里有一个潜在的缺陷: has_and_belongs_to_many
和has_many :through
关联在连接表中有记录,以及相关的记录。 因此,当我们调用其中一种删除方法时,应该删除哪些内容?
答案是假设关联上的删除是关于删除所有者和关联对象之间的链接,而不是必然是关联对象本身。 因此,使用has_and_belongs_to_many
和has_many :through
,连接记录将被删除,但关联的记录将不会被删除。
如果你考虑一下这是有道理的:如果你要调用post.tags.delete(Tag.find_by_name('food'))
你会希望food
标签与post
取消链接,而不是标签本身是从数据库中删除。