I have two links:
<%= link_to("Edit", edit_product_path(product.id)) %>
<%= link_to("Delete", product, :method => :delete) %>
The generated links are:
<a href="/products/81/edit">Edit</a>
<a href="/products/81" data-method="delete" rel="nofollow">Delete</a>
When clicking both on Edit
and on Delete
, the GET
method is used.
How Rails decided which method to use ?
What does data-method="delete"
and rel="nofollow"
mean in the Delete
link ?
Browsers usually support GET and POST HTTP methods. To emulate PUT and DELETE verbs, Rails injects a special _method
parameter when a form is submitted.
You specify the method you want to use by passing the :method
option, as you did.
<%= link_to("Action with DELETE", path_to_something, :method => :delete) %>
<%= link_to("Action with PUT", path_to_something, :method => :put) %>
Unless specified, the default value is GET
.
Starting from Rails 3, Rails uses unobtrusive JavaScript to handle the DELETE method. It passes the HTTP verb in the data-method
attribute, which is an HTML 5 feature.
In your case, it doesn't work because you probably forgot to include a JavaScript library (e.g. Prototype or jQuery) and the Rails adapter.
Make sure you are using either jQuery or Prototype, and you are including the rails.js
javascript file.
Also, don't forget to add the csrf_meta_tag
.
<%= csrf_meta_tag %>
If you want to learn move, I wrote an article about Unobtrusive JavaScript in Rails 3 a few months ago.