gpt4 book ai didi

ruby-on-rails - 充当偏执狂 : really destroy record that has paranoid children

转载 作者:行者123 更新时间:2023-12-05 02:15:31 24 4
gpt4 key购买 nike

我正在使用 ActAsParanoid gem 来软删除一些记录,比如说 child 。 parent 并不偏执,我希望在摧毁 parent 时, children 真的被摧毁了。

class Parent < ApplicationRecord
has_many :children, dependent: :destroy
end

class Child < ApplicationRecord
act_as_paranoid
belongs_to :parent
end

我现在看到子项正在被软删除,以防止父项被销毁,因为子项中的引用变得无效。 parent 被摧毁后,我怎样才能让 child 真正被摧毁? (我想知道我是否可以避免自定义回调)

更新:

使用 dependent: :delete_all 如果有一个子项先前已被删除,则会出现相同的错误。

最佳答案

实际上,Paranoia gem 并未考虑您的情况。如果您查看文档,则有 examples适用于其他场景,但不是您想要的场景。

has_many 关联中的 dependent 属性只接受 destroy, delete_all, nullify , restrict_with_exception, restrict_with_error 如你所见 here .所以你不能在那里调用 really_destroy!

幸运的是,有一个 before_destroy可用于在每个子级中执行 really_destroy! 的回调。尝试这样的事情:

class Parent < ApplicationRecord
has_many :children

before_destroy :really_destroy_children!

private

def really_destroy_children!
children.with_deleted.each do |child|
child.really_destroy!
end
end

end

关于ruby-on-rails - 充当偏执狂 : really destroy record that has paranoid children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51750601/

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