Ruby on Rails

Confirm delete a record

Deleting a record from a list (for example in the index view) can be performed using the button_to method.

This method will create an html form, with a few elements inside of it: a button and two hidden input elements.

One hidden element is the authenticity token that makes sure the form is safe.

<input type="hidden" name="authenticity_token" value="SIIEsaU4c..." autocomplete="off">

The second hidden element is a field specifying the method to be used by the routing system to figure out which action to run (the destroy action).

<input type="hidden" name="_method" value="delete" autocomplete="off">

The form itself will make a POST request to /posts/:id with the id of the record to delete.

To prevent accidental removal of records, we can add a confirmation modal dialog with the data-turbo-confirm attribute on the form element.
If the user cancels the dialog, the form will not be submitted.

Here’s how to add the data-turbo-confirm dialog to the form, from inside the button_to method:

  <%= button_to "Delete", post_path(post),
    method: :delete,
    form: {data: {turbo_confirm: "This post will be deleted immediately. Do you want to continue?"}},
    class: "inline-block underline text-indigo-600" %>
← All posts Recent blog posts →