I wanted to create a basic "destroy" link in Rails today, so I wrote this:
<%= link_to "destroy me", @company, :method=>:delete
%>
The generated code was:
<a href="/companies/1"
data-method="delete"
rel="nofollow">destroy me</a>
In my routes, the usual
resources :companies
And my destroy action was in my controller.
But anytime I would click on the link, I would be redirected to the show
action. Weird.
It turned out I didn't include the following line in my layout:
<%= javascript_include_tag :defaults %>
After including it, the destroy link worked!
Why? Why would I need to include the default javascript tags to make this work?
And since I don't want to use prototype, how do I only include the files I need?
Since 3.0, Rails form helpers generate clean HTML tags with HTML5 data attributes (data-method in your example). To support these data attributes, rails.js is required for prototype. If you use jQuery, then the jQuery version (https://github.com/rails/jquery-ujs) is needed.
Simply put, rails.js together with the javascript framework (prototype or jquery) does some magic to hook click and other events on a tag, other wise when you click a link, a normal click happens because without javascript, the link is a normal link.
It's because of the limitations of html and the fact that anchor tags cannot submit requests with any method other than GET.
If you look at rails.js (which will be included with :defaults
), when you click a link which has "data-method", it generates and submits a form which uses the correct http method to submit to the url specified in the anchor tag.
It's a hack of a workaround, but there's not really any other option to make normal anchor tags submit DELETE requests (or any other HTTP verb than GET).
If you don't want to use js, use a form (perhaps using button_to rather than link_to) to make the request. If you create your own helper to build the form, you could make it use the button tag (as opposed to an input which rails builds) which is quite easy style to make to look like a normal link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With