Rails的link_to方法:何时删除 [英] Rails' link_to method: GETing when it should DELETE

查看:133
本文介绍了Rails的link_to方法:何时删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Michael Hartl的Rails教程,并出于以下原因而编写以下代码:

I'm following Michael Hartl's Rails Tutorial, and for some reason the following code:

<%= link_to 'delete', user, :method => :delete, :confirm => "You sure?",
                                :title => "Delete #{user.name}" %>

发出GET请求(通过检查Rails服务器日志进行验证).我还验证了以下行在我的应用程序视图中:

Issues a GET request (as I verified by checking the rails server log). I also verified that the following line is in my application view:

<%= javascript_include_tag :all %>

我不太了解的一件事,这可能是我的问题所在:删除"方法在哪里定义?我在 Hartl的源代码中进行了验证,他在控制器,而不是删除".但是,即使我将link_to更改为:method =>:destroy,它也只会发出GET.

One thing I didn't quite understand, and it's probably the source of my problem: where is the "delete" method defined? I verified in Hartl's source code that he defines a "destroy" method in the controller, not "delete". But even if I change the link_to to :method => :destroy, it just issues a GET.

我正在使用Rails 3.1.有提示吗?

I'm using Rails 3.1. Any tips?

推荐答案

大多数浏览器实际上并不支持DELETE动词,因此Rails通过修改其生成的HTML来伪造它. Rails附加了一个名为data-method的HTML5属性并将其设置为"delete".因此,当用户单击链接时,它实际上是作为GET请求发出的,但是data-method属性允许使用Rails的一些魔术,这意味着您的路由代码应将其识别为DELETE请求.

Most browsers don't actually support the DELETE verb, so Rails fakes it by modifying the HTML it generates. Rails tacks on a HTML5 attribute called data-method and sets it to "delete". So when a user clicks on the link, it is actually issued as a GET request, but the data-method attribute allows for some Rails magic and means your routing code should recognize it as a DELETE request.

您可以自己在控制台中对其进行测试.运行bundle exec rails c进入控制台,并查看生成的HTML:

You can test it yourself in the console. Run bundle exec rails c to get into the console, and look at the HTML that this generates:

helper.link_to "delete", "foobar/delete", :method => 'delete'

HTML应该如下所示:

The HTML should look like this:

<a href="foobar/delete" data-method="delete" rel="nofollow">delete</a>

这篇关于Rails的link_to方法:何时删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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