views:

111

answers:

2

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 
+1  A: 

This might help:

http://www.themodestrubyist.com/2010/02/24/rails-3-ujs-and-csrf-meta-tags/

cowboycoded
Up vote for the link. I'm accepting his answer because he's included the help and his explanation was thorough.
Jamis Charles
+3  A: 

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.

vonconrad
Great answer. Thank you.
Jamis Charles