How to Soft Delete in Rails

There are many times where you don't want to permanently delete a record from the database, however you don't want to build an archiving system manually, that's where gems such as Paranoia come in.

Here is how to set it up.

Add the gem to your Gemfile and run bundle:

gem "paranoia", "~> 2.2"

 

Now you will need to add a migration to have a deleted_at column for the models that you want to have the archiving functionality. If you want to add it to a model such as Post, you can build the migration like this:

rails g migration add_deleted_at_to_posts deleted_at:datetime:index

 

This will create a migration file with the correct parameters, after that you can run rails db:migrate to add the column to the table.

Now all you have to do is add the method call acts_as_paranoid to the model that you want the functionality added to, like this:

class Post < ApplicationRecord
  acts_as_paranoid
end

 

Now if you delete a record in the application (using the standard destroy method) it will appear to be removed from the database. However if you run the query:

Post.only_deleted

 

You'll see that the record is safe and sound. You can also view all of the posts with the query:

Post.with_deleted

 

And you'll see the archived and live records.

If you want to unarchvie a record you can run the code:

Post.restore(id)

 

And it will make the record active again.