首页 > 解决方案 > 充当偏执狂:真正摧毁有偏执儿童的记录

问题描述

我正在使用 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-railsacts-as-paranoid

解决方案


Paranoia实际上, gem中没有考虑您的情况。如果您查看文档,则有其他场景的示例,但不是您想要的示例。

dependent如您在此处看到的,关联中的属性has_many仅接受destroy, delete_all, nullify, 。所以你不能在那里打电话。restrict_with_exceptionrestrict_with_errorreally_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

推荐阅读