作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有这样的关系:
Parent
has_many :children
Child
belongs_to :parent
我想做的是如果没有更多的 child 离开,删除 parent 。所以要做到这一点,我有:
Child
before_destroy :destroy_orphaned_parent
def destroy_orphaned_parent
parent.children.each do |c|
return if c != self
end
parent.destroy
end
这很好用,但是我也想将父级的删除级联到子级。例如。我通常会这样做:
Parent
has_many :children, :dependent => :destroy
这会导致 WebRick 服务器在我测试时崩溃。我假设这是由于最后一个 child 删除父删除 child 等的无限循环。
我开始考虑是否有更好的方法来做到这一点?有人有主意吗?有没有办法防止这种递归?
最佳答案
我是通过以下方式完成的:
before_destroy :find_parent
after_destroy :destroy_orphaned_parent
def find_parent
@parent = self.parent
end
def destroy_orphaned_parent
if @parent.children.length == 0
@parent.destroy
end
end
根据 Anwar 的建议,这也可以使用 around
回调来完成,如下所示:
around_destroy :destroy_orphaned_parent
def destroy_orphaned_parent
parent = self.parent
yield # executes a DELETE database statement
if parent.children.length == 0
parent.destroy
end
end
我尚未测试上述解决方案,因此如有必要,请随时更新。
关于ruby-on-rails - 删除孤立的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5866378/
如果数据很大,我正在使用 orphan 属性在打印时添加分页符它在 chrome 和 IE 中工作但在 FireFox 中不支持. docprint.document.write('
如果我从“Default.aspx”等进行 AJAX PageMethod 或 WebMethod 调用,然后在初始 PageMethod 返回之前快速导航到另一个页面(例如“Settings.asp
我是一名优秀的程序员,十分优秀!