And*_*Vit 9 activerecord ruby-on-rails has-many-through
使用常规has_many
,可以选择:dependent => :destroy
在删除父记录时删除关联.有了has_many :through
,可能还有其他父母与子记录相关联,因此:dependent => :destroy
没有任何效果.
如何确保子记录在从最后一个HMT关联中孤立后被删除?
And*_*Vit 13
我发现的解决方案似乎是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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4236 次 |
最近记录: |