Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

Interesting. I can confirm that link_to with the ":method => :delete" option does work in the default scaffold. However, in trying to build a project without scaffolding, I cannot get link_to to work. button_to works with no problem, using the same parameters that failed with link_to.

In my HEAD tag I have the required javascript includes:

javascript_include_tag :defaults
csrf_meta_tag

Very confusing. I couldn't figure out what "secret sauce" scaffolding puts into play to make link_to work. While Rob's assertion that link_to delete does not work in Rails 3, may not be technically accurate, I found it practically accurate. Thanks Rob, I had been stuck for hours until I saw your post.

You can't use a link for a delete in rails 3 You need to use a button_to eg.

<%= button_to("Delete", product, :method => :delete) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top