Beginner Tip: Soft Deletes in Rails

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

  1. In the destroy method, toggle the active flag to mark the object as inactive
  2. use a named scope to access only the active objects instead of all of them

Let’s look at some code.

← Previous post

Next post →


  1. Have you seen the destroyed_at gem? We quite like it at AdParlor, although its the opposite of your preferred “active” object. I think the concept of deleted (destroyed) versus status can be two entirely different things.

    class Article < ActiveRecord::Base
    include DestroyedAt

    (with the appropriate migrations etc)



    It also provides some nice defaults, like filtering out destroyed objects as the default scope etc.

Comments are closed.