In my Rails app, I need scripts to behave differently depending on which controller and action they are served from. So in my ApplicationController, I make these available like so:
before_filter :save_action_controller
def save_action_controller
@action = action_name
@controller = controller_name
end
And in an erb-filtered javascript file I have this:
window.controller = <%= @controller || 'undefined' %>;
window.action = <%= @action || 'undefined' %>;
But it seems that @controller and @action are both nil in this context? However, I can access them from views and helpers. Also, I don’t see how this can go by without raising an exception, if I were really trying to access ‘non-existent’ variables?
What do I need to do to access this from javascript? Is there a preferred method?
This railscast episode has some info on passing data to javascript.
There are several ways to do it but one nice approach is to use data attributes (as shown in railscast). You can define it with html like so:
and then access it via javascript