Soft delete for Rails Active Storage Blobs and Attachments

942 Views Asked by At

Can someone help on implementing soft deletion for Rails Active storage Blobs and Attachments.

I am using acts_as_paranoid gem for other models, but how to use this in Active storage blobs and attachments.

How to overwrite this model?

Thanks in Advance.

1

There are 1 best solutions below

0
On

So I've got a possible solution that seems to work. I would appreciate any feedback as it doesn't feel particularly solid.

In my app Employees have files and I want to be able to archive the employee, then get their files back when restoring the Employee record.

#/models/employee.rb
class Employee < ApplicationRecord
acts_as_paranoid  

def destroy
    @employee = Employee.find(params[:id])
    
    #create a temporary employee object to attach all files to.
    @temp_employee = Employee.new(name:"temp", position: "temp")

    #attach each of the original employee's files to the temp employee
    @employee.files.each do |f|
      @temp_employee.files.attach(f.blob)
    end

    #soft delete the employee
    @employee.destroy
    
    #re-attach all the files back 
    @temp_employee.files.each do |n|
      @employee.files.attach(n.blob)
    end
    
    @employee.save! 
   #employee is soft deleted, and the files are attached to the record
end
end