【问题标题】:Act As Paranoid: really destroy record that has paranoid children充当偏执狂:真正摧毁有偏执儿童的记录
【发布时间】:2018-08-08 15:37:30
【问题描述】:

我正在使用 ActAsParanoid gem 软删除一些记录,比如说孩子们。父母不是偏执狂,我希望在父母被摧毁时,孩子会被真正摧毁。

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

class Child < ApplicationRecord
  act_as_paranoid 
  belongs_to :parent
end

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

更新:

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

【问题讨论】:

    标签: ruby-on-rails acts-as-paranoid


    【解决方案1】:

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

    has_many 关联中的dependent 属性仅接受destroydelete_allnullifyrestrict_with_exceptionrestrict_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
    

    【讨论】:

    • 这就是我所害怕的。感谢您确认、指向文档并添加代码。
    • 我编辑了它:添加了一个无范围的,因此它也会硬删除软删除的子项
    • @LeticiaEsperon 随意在 gem 存储库中添加拉取请求,以使场景可用;)
    • 有一个错字,每个后面都有一个额外的点,但它不允许我编辑它@DanielBatalla
    • 已修复!谢谢@LeticiaEsperon
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多