问题描述
我有这样的关系:
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.
我开始认为有更好的方法来做到这一点?有人有想法么?有没有办法防止这种递归?
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
(使用像那个一样的声明http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a3f12d578f5a2619)
You could delete orphaned parents inan
after_destroy
(find them using astatement like the one onhttp://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a3f12d578f5a2619)
您可以在包含父 ID 的 before_destroy
中设置一些实例变量,然后在 after_destroy
回调中根据此 ID 进行查找并决定是否删除那里的父母基于计算孩子
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
这篇关于删除孤立的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!