gpt4 book ai didi

ruby-on-rails - 删除孤立的父级

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:19 25 4
gpt4 key购买 nike

我有这样的关系:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com