When you are learning Rails, all of the tutorials teach you how to delete an object from the application. This means actually deleting a row from a table in the database. However, this is actually quite rare in the real world. There are laws and other complications that restrict the ability of really deleting data. This means that we need to hide the information instead of deleting it. This is called a “soft delete” or a “logical delete”. When you remove the data from the DB, it is called a “physical delete”.
So how does one go about hiding information instead of removing it? It’s actually quite simple.
First, you need to create a flag on your model that shows whether an object is deleted or not. I personally like to say whether something is active instead of deleted, because it means that when I go looking for things to display, I am looking for a positive. For this example, we will be hiding blog articles.
A soft delete has two parts
- In the destroy method, toggle the active flag to mark the object as inactive
- use a named scope to access only the active objects instead of all of them
Let’s look at some code.