0

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?

1 Answer 1

6

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:

<h1>Products</h1>

<div id="products" data-url="<%= products_url %>">
  Loading products...
</div>

and then access it via javascript

jQuery ->
  alert $('#products').data('url')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.