'Rails 7 - link_to with method :delete still performs GET request
I am trying to get this link to work, performing a DELETE
request:
<%= link_to "Sign Out", destroy_user_session_path, method: :delete %>
However when I click on it, my browser still performs a GET
request (which fails for obvious reasons):
I have read on multiple other forum posts, that this might have something to do with jquery not being included. They mentioned you would need to un-comment a line in app/javascript/application.js
, however mine is pretty empty:
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
These forum posts were also quite old, so I suspect something has changed in the meantime.
Solution 1:[1]
As suggested here, the following will suffice:
<%= link_to "Sign Out", destroy_user_session_path, data: { "turbo-method": :delete } %>
I have tested this in my project and it seems to work fine. Thanks also to @alexts, you basically figured this out too, however the comment on GitHub even eliminated the double-request.
Solution 2:[2]
There are (at least) two ways to delete something in rails 7:
Using button_to
(more prefered IMHO):
<%= button_to 'Sign Out', destroy_user_session_path, method: :delete %>
Renders an HTML form which sends a POST
request with a hidden _method
attribute with 'delete' value. Rails will treat this as if it has a DELETE
method (and route it to products#destroy
or whatever your routes are saying). Do not use this one within another form (HTML forbids one form inside another).
Using link_to
:
<%= link_to 'Sign Out', destroy_user_session_path, data: {turbo_method: :delete} %>
Renders a simple a
tag with data-turbo-method
attribute. This link sends a real DELETE
request.
If your destroy
action ends with a redirect_to
, some browsers will redirect to a new location with DELETE
method (causing errors), so make sure to add status: :see_other
parameter to redirect_to
, like the guides suggest.
Confirmation
If you want to add confirmation prompt to a button above:
<%= button_to 'Sign Out', destroy_user_session_path, method: :delete,
form: {data: {turbo_confirm: 'Are you sure?'}} %>
If you want to add confirmation to a link above:
<%= link_to 'Sign Out', destroy_user_session_path,
data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |