Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete link sends "Get" instead of "Delete" in Rails 3 view

I'm using Rails 3 and have have a page that outputs a list of posts from the database. I'd like to be able to delete a post from a link.

The 2nd example below works, but the first doesn't. Anybody know why the first won't work? My view contains:

# this link sends a "GET" request which asks for the #show function  
<%= link_to 'Delete', post, :method => :delete %>

# this link sends the proper "DELETE" request which asks for the #destroy function
<%= button_to 'Delete', post, :method => :delete %>

My routes file contains the following:

resources :posts 
like image 337
Jamis Charles Avatar asked Sep 23 '10 02:09

Jamis Charles


4 Answers

Make sure that your <head> section in the layout includes the following:

<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

In Rails 3, the delete requests are being handled with the help of JavaScript to ensure that the request is being sent correctly. If you don't have the csrf meta tags and the required JavaScript code, delete links won't work. The :defaults JavaScript files include--among others--prototype.js, and application.js. The latter contains the stuff that makes the link work, but relies on the Prototype framework.

If you don't want to use the default Prototype JavaScript libraries, there are ports of application.js for several other frameworks. You can find the jQuery one here, for instance.

Buttons will still work regardless of JavaScript, as the HTML code generated with button_to includes all necessary information by itself. This is why you're seeing the button work while the link doesn't.

like image 129
vonconrad Avatar answered Nov 01 '22 19:11

vonconrad


looks like

<%= javascript_include_tag :defaults %>

is no longer supported

http://apidock.com/rails/ActionView/Helpers/AssetTagHelper/JavascriptTagHelpers/javascript_include_tag

Instead, you should use

<%= javascript_include_tag 'application' %>
like image 17
alikk Avatar answered Nov 01 '22 19:11

alikk


I had the same problem in rails 5.2.3 and this helped me:

layout head:

<%= javascript_include_tag "rails-ujs" %>

config/initializers/assets

Rails.application.config.assets.precompile += %w( rails-ujs.js )
like image 7
Romalex Avatar answered Nov 01 '22 18:11

Romalex


In my case, I was using following.

<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

I was also using jQuery by including jQuery just below default prototype JS. That was causing some sort of conflict.

like image 3
Ninad Avatar answered Nov 01 '22 18:11

Ninad