Search code examples
ruby-on-railsruby-on-rails-7turbo

How to call confirm prompt using button_to in Rails with Turbo


Previously in Rails when using the button_to tag, it was possible to use a confirmation dialog like this

<%= button_to 'Destroy', @post, method: :delete, data: { confirm: 'Are you sure?' } %>

data: { confirm: 'Are you sure?' } is Rails magic data attribute that was used by @rails/ujs library under the hood

Following Rails 7, this library is no longer on by default. Instead of this Rails use Turbo library

And now this code does not work

There is no information in official Rails docs and Turbo handbook

What I tried

<%= button_to 'Destroy', @post, method: :delete, data: { turbo_confirm: 'Are you sure?' } %>
<%= button_to 'Destroy', @post, method: :delete, data: { 'turbo-confirm': 'Are you sure?' } %>

But there is no result

I didn't find any solution on SO but found on Hotwire forum. This solution with Stimulus action. I just improve it a little

<%= form_with model: @post, method: :delete, data: { controller:  'confirmation', message: 'Are you sure?', action: 'submit->confirmation#confirm' } do |f| %>
  <%= f.submit 'Destroy' %>
<% end %>
// app/javascript/confirmation_controller.js
import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  confirm(event) {
    if (!(window.confirm(this.element.dataset.message))) {
      event.preventDefault()
    }
  }
}

It works but it's quite difficult and looks ugly, and we are used to Rails being cool


Solution

  • In Rails with Turbo without rails-ujs to call confirmation popup window with button_to we need to use code like this

    <%= button_to 'Destroy', @post, method: :delete, form: { data: { turbo_confirm: 'Are you sure?' } } %>
    

    or

    <%= button_to 'Destroy', @post, method: :delete, form: { data: { 'turbo-confirm': 'Are you sure?' } } %>
    

    Both generate data-turbo-confirm attribute

    So we need to add this attribute not to submit button (like in rails-ujs) but directly to form containing this button (let me remind you this tag generates a form with button)