How to Create an Undo Action with Rails
Tags: rails, ruby, hotwire, webdev
Published: 2024-06-20 10:00:00

_This article was originally published on [Rails Designer](https://railsdesigner.com/undo-actions/)._

---

An undo-action is a common UX paradigm in web-apps. You delete, archive or send something and can then undo that action. Often you see it with a flash/notification component like this one:


![Notification component showing Email deleted text + an undo action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnhecdh9msph3ynwrc71.jpg)

(example coming from Rails Designer's [NotificationComponent](https://railsdesigner.com/components/notifications/))

After the message was soft-deleted, or put in the “trash”, the notification confirms the action and gives the option to undo.

Some time ago Gmail added the option to “undo” sending an email. Of course, the sending wasn't actually undone, but rather the sending had not yet happened.


![Showing Gmail's undo send notification](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y72ihx9idyziaan4vjo6.jpg)

Other examples could be:

- Undo Archive;
- Undo Merge;
- Undo Mark as Read;
- Undo Publish;
- Undo Schedule.

How each action is actually made “undone” is different on the back-end side. `Undo Archive` might simply remove the `archived_at` timestamp, similarly with `Undo Mark as Read`. But `Undo Merge` might be quite more complicated to pull off.

So let's go over the product bit, that's the same for each action. For this article I've chosen an “Undo Email Delete”.


## Undo Action or Confirm Action?

But when to choose an Undo-action or a [Confirm Dialog](https://railsdesigner.com/custom-confirm-dialog/)?

- Undo action: do the action, then give the option to undo it;
- Confirm action: ask before doing the action.

They both have there place, depending on the action and the consequence. This is the rule-of-thumb I typically use:

Use a **Confirm Dialog** when the action simply cannot be undone. You actually delete the record from the database or the action is so destructive to one or many rows it's impossible to reverse.

And an **Undo action** can then be used for non-destructive actions: you soft-delete a record, you add the sending to a background queue with a delay or the action simply sets a timestamp (eg. `archived_at`).

Next to that, with the examples of deleting or archiving a record, there might not be a need for an undo action. Most users are familiar with these patterns. Also if you rename the action to **Move to Bin** instead of just **Delete** they certainly will know where to find the record and move it back.

One last point when building a new feature: I typically would default to the Confirm Dialog's, especially because [Rails Designer](https://railsdesigner.com/docs/utilities/#custom-confirm-dialog) makes it super easy to add beautiful ones. This is the kind of lean-building I've been practicing for over eight years. Your users will let you know once it annoys them!


## Build an Undo Action with Rails

_Note: I'm assuming you have access to [Rails Designer's UI Components Library](https://railsdesigner.com/)._

With that all out of the way, let's build the **Undo Email Delete** with Rails. Let's first set the stage:

You have a model named `Email` (`app/models/email.rb`) that has a `deleted_at` timestamp. You could also use something like the [Discard gem](https://github.com/jhawthorn/discard) (my preferred choice).

Let's focus on the controller to soft-delete the email.

```ruby
# app/controllers/emails_controller.rb
class EmailsController < ApplicationController
  before_action :set_email, only: %w[destroy]
  # …
  def destroy
    @email.update(deleted_at: Time.current)

    redirect_to emails_path, notice: "Email deleted successfully."
  end

  def set_email
    @email = Email.find(params[:id])
  end
  # …
end
```

Currently it's your standard Rails controller. Onto the turbo stream response.

```ruby
# app/views/emails/destroy.turbo_stream.erb
<⁠%= stream_notification "Your message was deleted", primary_action: {title: "Undo", path: restore_email_path(@email), method: :patch}, time_delay: 10, progress_indicator: "progress_bar" %>
```

For this to work, grab the **[Undoable action variant](https://railsdesigner.com/components/notifications/#undoable-action-for-10-seconds)** from the **NotificationComponent**. If you don't have Rails Designer ([get it here](https://railsdesigner.com/pricing/)!), check out this article about [more advanced flash messages in Rails](https://railsdesigner.com/flash-in-rails/#more-advanced-flash-messages).

If you wonder where `stream_notification` comes from: it's [a helper that's included in Rails Designer](https://railsdesigner.com/docs/view-helpers/#stream-notification).

The astute reader noticed the `restore_email_path` helper. Let's create the route first and then controller:

```ruby
# config/routes.rb
# …
resources :restore_emails, only: [:update]
```

```ruby
# app/controllers/restore_emails_controller.rb
class RestoreEmailsController < ApplicationController
  def update
    @email.update(deleted_at: nil)

    redirect_to emails_path, notice: "Email was successfully restored."
  end

  private

  def set_email
    @email = Email.find(params[:id])
  end
end
```

Again, your standard Rails controller. Let's create a Turbo Stream response for the update action.

```ruby
# app/views/emails/update.turbo_stream.erb
<⁠%= stream_notification "Moved from the Bin" %>
```

Based on your app's set up you can extend this response by injectin the previously-deleted email in the email list. This could be with a Turbo Stream append action (`turbo_stream.append("inbox", partial: "emails/email", locals: { email: @email })`) or by refreshing if it's a turbo frame (`turbo_stream.turbo_frame_reload(#inbox)`; this is using the [turbo_power](https://github.com/marcoroth/turbo_power-rails) package).

And that's how simple adding an undo action is with Rails and Turbo. Again: undo action can be an elegant UX, but keep in mind the context it's used for and at what stage your product is.

Anything that's missing or unclear? Let me know below.