I have a controller#action that defines an instance variable:
@min_rating = 4
In the view I have the following:
<%= javascript_tag do %>
min_rating = <%= @min_rating %>
<% end %>
Then in my Coffeescript I can do the following:
jQuery ->
alert min_rating
And if I am on the page of that view, it works properly.
However, if I am on another view, I get a JS error saying that the var min_rating is not defined:
Uncaught ReferenceError: min_rating is not defined
This is because I load all the JS for all the views in the application.js:
//= require_tree .
So, my question is: What is the best way to deal with this in Rails?
It depends on your goals. One simple option is to check whether min_rating is defined in javascript before referencing it:
Or you can make sure that min_rating is defined on every page – possibly by moving that javascript_tag call to a decorator and falling back to a default value. Whether or not that makes sense for your application is up to you.
Or you could try to avoid loading the script that references on min_rating on pages where it is not needed. But that would mean that you would not be able to use the same combined javascript file on every page.