Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are default javascript files required to create a destroy link in rails?

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?

like image 291
Guillaume Flandre Avatar asked Jan 29 '11 13:01

Guillaume Flandre


2 Answers

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.

like image 122
James Chen Avatar answered Oct 31 '22 04:10

James Chen


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.

like image 41
idlefingers Avatar answered Oct 31 '22 04:10

idlefingers