问题描述
我正在关注 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 方法:获取何时应该删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!