ruby-on-railsacts-as-paranoid

Act As Paranoid: really destroy record that has paranoid children


I'm using ActAsParanoid gem to soft delete some records, let's say the children. The parent is not paranoid, and I want that on destroy of the parent, the children get really destroyed.

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

class Child < ApplicationRecord
  act_as_paranoid 
  belongs_to :parent
end

I'm now seeing that the children are being soft deleted, preventing the parent to be destroyed because the reference in the child becomes invalid. How can I make the children be really destroyed after the parent gets destroyed? (I want to know if I can to avoid custom callbacks or not)

Update:

Using dependent: :delete_all gives the same error if there is one of the children that had been previously deleted.


Solution

  • Actually your case is not being considered in Paranoia gem. If you see the documentation, there are examples for other scenarios, but not the one you want.

    dependent attribute in has_many association only accepts destroy, delete_all, nullify, restrict_with_exception, restrict_with_error as you can see here. So you can't call really_destroy! there.

    Luckily, there is a before_destroy callback that you can use to perform really_destroy! in each children. Try something like this:

    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