What’s the best way to implement gmail style “undo” in Rails?

Spread the love

Question Description

I think it important to have an “undo” method ala gmail when destroying records instead of displaying an annoying popup that says, “Are you sure?“.

The way that I’ve implemented this is to have a “deleted_at” timestamp column in the model which gets timestamped when destroy method is called

def destroy
  @foo = Foo.find(params[:id])
  @foo.update_attribute(:deleted_at, Time.now)

To revert/undo I’ll just set the same column to nil

def revert
  @foo = Foo.find(params[:id])
  @foo.update_attribute(:deleted_at, nil)

I’ll just have to add a condition to filter off “deleted” foos when I call the find method. Perhaps set a cron or background task to really destroy “deleted” foos after some time.

Works for me and easy to implement but I’m curious as to if there’s a better way to implement this feature? Maybe there’s a plugin or gem that provides this that I don’t know about?

Practice As Follows

There are indeed some plugins that can be found at Agile Web Development.

Here are the links and summaries for the plugins which seem to match your description:

  1. Acts as Paranoid: Make your Active Records “paranoid.” Deleting them does not delete the row, but set a deleted_at field. Find is overloaded to skip deleted records.
  2. Acts as soft deletable: Provides the ability to soft delete ActiveRecord models.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.