Logical deletion using Gem paranoia

memorandum

Since I used logical deletion when creating my own application this time, I will record it as a memorandum. Since you are a beginner in programming, please point out any mistakes! This time, we are developing using rails and MySQL.

What is logical deletion?

The general deletion is called physical deletion, and if you delete it, the data will also be deleted from the DB. On the other hand, logical deletion is different from general deletion, and it means that the data remains in the DB as if it was deleted. It is also used to display the deletion history and restore data.

Step 1 Introduction of Gem

Introduce Gem's paranoia, which greatly cuts the trouble of logical deletion. Write in Gemfile and bundle install in terminal

gem 'rails_12factor'

Step 2 Add column

When logical deletion is performed, the date and time of deletion is inserted in this column, and the deletion flag can be set.

class AddDeletedAtToCategories < ActiveRecord::Migration[6.0]
  def change
    add_column :categories, :deleted_at, :datetime
  end
end

If it is correct, please do $ rails db: migrate. Write the following in the model.

Step 3 Edit the model

acts_as_paranoid

Summary

With the above settings, the logical deletion setting using paranoia is complete! I think it would be quite difficult to implement it normally, but I was able to implement it easily by using paranoia! I hope it will be useful for beginners in programming.

Recommended Posts

Logical deletion using Gem paranoia
[Rails] Implement event end function (logical deletion) using paranoia (gem)
[RSpec] Unit test (using gem: factory_bot)