Rails的link

编程入门 行业动态 更新时间:2024-10-28 16:29:56
本文介绍了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

本文发布于:2023-10-09 17:51:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476371.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails   link

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!