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