删除链接发送“获取"而不是“删除"在 Rails 3 视图中 [英] Delete link sends "Get" instead of "Delete" in Rails 3 view

查看:44
本文介绍了删除链接发送“获取"而不是“删除"在 Rails 3 视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Rails 3,并且有一个页面可以输出数据库中的帖子列表.我希望能够从链接中删除帖子.

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 

推荐答案

确保布局中的 部分包括以下内容:

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

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

在 Rails 3 中,删除请求是在 JavaScript 的帮助下处理的,以确保请求被正确发送.如果您没有 csrf 元标记和所需的 JavaScript 代码,删除链接将不起作用.:defaults JavaScript 文件包括——其中包括——prototype.js 和 application.js.后者包含使链接工作的内容,但依赖于 Prototype 框架.

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.

如果您不想使用默认的 Prototype JavaScript 库,那么还有适用于其他几个框架的 application.js 的端口.例如,您可以在 此处 找到 jQuery one.

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.

不管 JavaScript 是什么,按钮仍然可以工作,因为使用 button_to 生成的 HTML 代码本身包含所有必要的信息.这就是为什么您看到按钮有效而链接无效的原因.

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.

这篇关于删除链接发送“获取"而不是“删除"在 Rails 3 视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆