删除孤立的父级 [英] Delete Orphaned Parent

查看:27
本文介绍了删除孤立的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的关系:

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?

推荐答案

一些想法:

  • 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)

您可以在包含父 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

这篇关于删除孤立的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆