Link_to does not work with delete method when app is created with --skip-javascript

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

does not work when application is created with --skip-javascript

but button_to works in any case

<%= button_to 'remove', post, method: :delete %>

is there a way to use link_to?

If I’m not mistaken the data-confirm option is part of rails ujs, which is not included when you skip the javascript

To add on to what @jonathanbruno said, the reason that button_to still works is because it does not require UJS to intercept the request. When using button_to with the method option, it creates a form with the button and this hidden field:

<input name='_method' value='delete' type='hidden' />

To my understanding, this hidden field is what allows the server to interpret the request as a delete request. I’m not sure if this happens at the Rack or Rails level, but it’s required since HTML doesn’t natively support put or delete requests.

If you dive into the source of Rails-UJS you can find this file. This is the source that allows for the use of method on link_to. This code shows that all it does is insert a form with the same hidden field that is generated with the button, and then it automatically submits it.

Hope this explanation helps. I definitely have had a lot of confusion about this in the past too.

1 Like

Even if you keep using rails-ujs, you won’t be able to create POST or DELETE links with Turbo. It won’t work: https://github.com/hotwired/turbo-rails#compatibility-with-rails-ujs

If you need to create a non-GET link, then you need to use button_to and style the button as a link.

4 Likes

I think only remote invocation wont work, I have a demo that currently works with hotwire+railsujs

My bad! @jonathanbruno is right.

I always used data-method with data-remote and I thought that the former depends on the latter. However, it is not the case and checking the rails-ujs source code confirms it.