.js.erb VS .js
.js.erb
files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the
$('#business_submit').click(...)
in your application.js or *.html.erb, and your create.js.erb could look like this:
alert('New object id: ' + <%= new_object.id %>);
This way, the javascript that is getting returned to the browser can be first rendered by Erb, allowing you to insert custom strings/variables/etc just like you can in .html.erb templates.
If I may contribute to the answer with my few cents...
The answer to your question is really simple :
A file ending with *.js.erb allows your file to be interpreted by ruby. (So you will be able to use rails helpers)
A file ending with *.js is a pure javascript.
You will never get a *.js file to work if you place any ruby code inside like:
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'orders_chart' },
title: { text: <%= gon.my_title_of_the_day.to_json %> },
});
})
The part <%= gon.my_title_of_the_day.to_json %>
will just generate an error because javascript knows nothing about ruby.
In order your *.js file works, you will have to statically change it every time the day changes:
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'orders_chart' },
title: { text: 'Monday' },
});
})
N.B. : If you use a *.js.erb, you will need in addition the "Gon" gem to pass data from your controller to JS though.
Now for your underlying question "why is my javascript code not working '" I can't answer because I'm no javascript expert and this is another story... ;-)
Per my view, the reason to have js.erb files is to gain access to rails helpers like the something_url
routes. I've found, most of the time, that those URLs are already embedded in the <form>
tag or something like that, so I have little need for it. Processing everything with .erb also prevents you from caching javascript as aggressively.
For those reasons, I think the most appropriate decision is to put javascript in the most unobtrusive place possible: application.js (or other static scripts). Especially with jQuery, that's really as it was intended.
By the way, javascript_auto_include
is a nice, tidy plugin for organizing your javascript according to the views that are rendered. Rather than stashing everything in application.js
, you might consider this.
js.erb versus js.rjs
One of these two (.erb
) is really for generating javascript from a template. This is the sort of thing you would include as a tag in the HTML. The other (.rjs
) is about controlling page content in an AJAX response, and would not be run until such an AJAXy call was made.