How to make a DELETE link to a rails resource?

If I want to make a DELETE link in rails, I will write the following code (in this example, to delete a user session in Devise):

<%= link_to('Logout', destroy_user_session_path, :method => :delete) %> 

This will turn into the following HTML:

 <a rel="nofollow" data-method="delete" href="/users/sign_out">Logout</a> 

Works fine, but I can't just put this HTML in a static HTML page. It will simply execute the GET request. I assume Rails includes some standard Javascript to turn the above link into one that actually executes a DELETE request. So, what is the correct way to have a link in a static HTML page to a Rails resource that performs a DELETE action? Should I find and capture Javascript Rails on all web pages that do this? Is there a better way?

+4
source share
3 answers

You cannot send a DELETE request with a binding, unfortunately - a traditional binding will only contact a GET request. In fact, you really cannot send a real DELETE request at all. If you want to make a delete link without javascript, the solution will be quite simple. Check 2.4 How do forms work with PUT or DELETE methods? in the official documentation . Basically, you can simply create a form that submits the URL of your resource using the DELETE method. It's pretty simple, and you don't need to rely on javascript to do the job. Hope this helps, good luck.

+6
source

Rails uses JavaScript to handle delete links.

It creates an invisible form and submits it when you click the link with the data-method attribute "delete"

See handleMethod at https://github.com/rails/jquery-ujs/blob/master/src/rails.js

Perhaps links to deleting your static pages will only work when rails.js (if you are using jQuery). If not, you can create a form as you do in handleMethod yourself.

+3
source

Since some of my colleagues are working on a native application in which the user may not have JavaScript enabled in their browsers, in such cases the delete link will not work, and we will get a show page instead of deleting .... If you are not sure, maybe Whether the user enables or disables JS in their browser, you can always generate a route using the GET or POST method for the delete action of your controller ... This approach will work for a static HTML page as well.

+3
source

Source: https://habr.com/ru/post/1443770/


All Articles