最后的has_many后销毁协会:通过记录被删除
-
12-09-2019 - |
题
通过定期has_many
,有:dependent => :destroy
的删除协会当父记录被删除的选项。随着has_many :through
,可能有相关子记录的其他家长,所以:dependent => :destroy
没有任何效果。
您如何确保他们从过去的HMT协会孤儿后子记录被删除?
解决方案
我已发现该溶液似乎是一个after_destroy
回调,如这样的:
class Parent < ActiveRecord::Base
has_many :children, :through => :parentage
after_destroy :destroy_orphaned_children
private
def destroy_orphaned_children
children.each do |child|
child.destroy if child.parents.empty?
end
end
end
其他提示
在该连接模型中,使用 “belongs_to的:模型,取决于:消灭”
例如,如果要摧毁病人一旦他们的医生被破坏,医生的has_many患者虽然约会
Class Appointment
belongs_to :doctor
belongs_to :patient, dependent: :destroy
Class Doctor
has_many :appointments, dependent: :destroy
has_many :patients, through: :appointments
Class Patient
has_many :appointments
has_many :doctors, through: :appointments
不隶属于 StackOverflow