How does Rails 3 decide which HTTP verb will be used when clicking the link generated by "link_to"?

I have two links:

<%= link_to("Edit", edit_product_path(product.id)) %> <%= link_to("Delete", product, :method => :delete) %> 

Generated Links:

 <a href="/products/81/edit">Edit</a> <a href="/products/81" data-method="delete" rel="nofollow">Delete</a> 

When you click on Edit and Delete , the GET method is used.

How did Rails decide which method to use?

What does data-method="delete" and rel="nofollow" mean in the Delete link?

+4
source share
3 answers

Browsers usually support the GET and POST HTTP methods. To emulate the verbs PUT and DELETE, Rails introduces a special _method parameter when submitting the form.

You define the method you want to use by passing the :method parameter, just like you do.

 <%= link_to("Action with DELETE", path_to_something, :method => :delete) %> <%= link_to("Action with PUT", path_to_something, :method => :put) %> 

If not specified, the default value is GET .

Starting with 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 function .

In your case, this does not work, because you probably forgot to include the JavaScript library (for example, Prototype or jQuery) and the Rails adapter.

Make sure you use jQuery or Prototype, and you include the rails.js javascript file. Also, be sure to add csrf_meta_tag .

 <%= csrf_meta_tag %> 

If you want to learn how to move, I wrote an article about unobtrusive JavaScript in Rails 3 a few months ago.

+7
source

Interesting. I can confirm that the link_to link with the option:: method =>: delete works in the standard scaffold. However, trying to build a project without scaffolding, I cannot get link_to to work. button_to works without problems, using the same parameters as with link_to.

In my HEAD tag, I have the necessary javascript:

 javascript_include_tag :defaults csrf_meta_tag 

Very confusing. I could not figure out which "secret sausages" are being inserted into the game to make link_to work. Although Rob’s claim that link_to delete doesn’t work in Rails 3 may not be accurate, I found it to be practically accurate. Thanks Rob, I got stuck for hours until I saw your message.

0
source

You cannot use the delete link in rails 3 You need to use button_to, for example.

 <%= button_to("Delete", product, :method => :delete) %> 
-1
source

Source: https://habr.com/ru/post/1332208/


All Articles