Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

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 
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...