删除孤立的父 [英] Delete Orphaned Parent
问题描述
我有关系,像这样:
Parent
has_many :children
Child
belongs_to :parent
我想要做的就是删除父,如果没有更多的留守儿童。因此,要做到这一点,我有:
What I want to do is to delete the parent if there are no more children left. So to do this I have:
Child
before_destroy :destroy_orphaned_parent
def destroy_orphaned_parent
parent.children.each do |c|
return if c != self
end
parent.destroy
end
这工作得很好,但是我的也的要级联父的删除孩子。例如。我通常会做的:
This works fine, however I also want to cascade the delete of the parent to the child. E.g. I would normally do:
Parent
has_many :children, :dependent => :destroy
这会使WEBrick服务器,当我测试它崩溃。我认为这是由于最后一个子项删除父删除子等的无限循环。
This causes the WebRick server to crash when I test it. I assume this is due to an infinite loop of the last child deleting the parent deleting the child etc.
我开始以为有更好的办法做到这一点?任何人有什么想法?有没有一种方法,以prevent这个递归?
I am starting to think that there is a better way to do this? Anyone have any ideas? Is there a way to prevent this recursion?
推荐答案
若干思考:
-
您可以删除孤立的家长 一个
after_destroy
(使用的是找到他们 像一个上发言 <一href="http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a3f12d578f5a2619">http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a3f12d578f5a2619)
You could delete orphaned parents in an
after_destroy
(find them using a statement like the one on http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a3f12d578f5a2619)
您可以设置在 before_destroy
一些实例变量包含了父母的身份证,然后以此为基础对这个ID查找在 after_destroy
回调,并决定是否要删除父那里的基础上数着孩子
You could set some instance variable in before_destroy
containing the parent's ID, then do a lookup based on this id in an after_destroy
callback and decide whether to delete the parent there based on counting the children
这篇关于删除孤立的父的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!