我有两个链接:
<%= link_to("Edit", edit_product_path(product.id)) %>
<%= link_to("Delete", product, :method => :delete) %>
生成的链接是:
<a href="/products/81/edit">Edit</a>
<a href="/products/81" data-method="delete" rel="nofollow">Delete</a>
当同时单击
Edit
和 Delete
时,将使用 GET
方法。Rails 如何决定使用哪种方法?
data-method="delete"
链接中的 rel="nofollow"
和 Delete
是什么意思? 最佳答案
浏览器通常支持 GET 和 POST HTTP 方法。为了模拟 PUT 和 DELETE 动词,Rails 在提交表单时注入(inject)了一个特殊的 _method
参数。
您可以通过传递 :method
选项来指定要使用的方法,就像您所做的那样。
<%= link_to("Action with DELETE", path_to_something, :method => :delete) %>
<%= link_to("Action with PUT", path_to_something, :method => :put) %>
除非指定,否则默认值为
GET
。从 Rails 3 开始,Rails 使用不显眼的 JavaScript 来处理 DELETE 方法。它在
data-method
属性中传递 HTTP 动词,这是一个 HTML 5 feature 。在您的情况下,它不起作用,因为您可能忘记包含 JavaScript 库(例如 Prototype 或 jQuery)和 Rails 适配器。
确保您使用的是 jQuery 或 Prototype,并且包含
rails.js
javascript 文件。另外,不要忘记添加
csrf_meta_tag
。<%= csrf_meta_tag %>
如果你想学move,我几个月前写过一篇关于Unobtrusive JavaScript in Rails 3的文章。
关于ruby-on-rails - 当单击 "link_to"生成的链接时,Rails 3 如何决定将使用哪个 HTTP 动词?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4449040/