Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a DELETE link to a rails resource?

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

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

That will turn into the following HTML:

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

Works great, except I can't simply put that HTML into a static HTML page. It will simply do a GET request. I assume Rails includes some standard Javascript to turn the above link to one that actually does a DELETE request. So what's the proper way to have a link on a static HTML page to a Rails resource that does a DELETE action? Should I find and grab that Javascript Rails includes in all webpages that does this? Is there a better way?

like image 601
at. Avatar asked Dec 16 '22 17:12

at.


1 Answers

You can't send a DELETE request with an anchor link, unfortunately - a traditional anchor link will only send a GET request. Actually, you can't really send a true DELETE request at all. If you want to make a delete link, without javascript, the solution is fairly easy. Check out 2.4 How do forms with PUT or DELETE methods work? in the official documentation. Basically, you can simply create a form that submits to the url of your resource, with a method of delete. It's pretty simple, and you don't need to rely on javascript to get the job done. Hope this helps, good luck.

like image 167
Brad Werth Avatar answered Dec 18 '22 12:12

Brad Werth