0

In my assets, I have a file called maps.js.erb, basically with only the following (debugging) content:

alert("<%= @map.width %>");

This JS file is loaded through the show.html.erb view belonging to maps.

<%= javascript_include_tag params[:controller] %>
<h1><%= @map.title %></h1>
…

The HTML file itself shows the map's title, e.g. when browsing to /maps/1/, since @map is defined in the controller. However, as soon as I include the JS file, I get the following error:

NoMethodError in Maps#show

Showing …/app/views/maps/show.html.erb where line #1 raised:

undefined method 'title' for nil:NilClass (in …/app/assets/javascripts/maps.js.erb)

  • Why is @map not available in the js.erb file?
  • How else can I access this instance variable defined in my controller?
slhck
  • 36,575
  • 28
  • 148
  • 201

3 Answers3

1

Ryan Bates did a screencast right on that topic - you might wanna check it out:

http://railscasts.com/episodes/324-passing-data-to-javascript


In the html.erb file, you can define the variables:

<%= javascript_tag do %>
  window.productsURL = "<%=j products_url %>";
  window.products = <%=raw Product.limit(10).to_json %>;
<% end %>
slhck
  • 36,575
  • 28
  • 148
  • 201
klaffenboeck
  • 6,297
  • 3
  • 23
  • 33
  • @slhck: thanks for updating my question. Still, I don't think that this is the way to go, since you changed from _unobtrusive JavaScript_ to _inline JavaScript_, which I don't consider a best practice. You might want to discuss this in the chat with me at some point. – klaffenboeck Apr 13 '12 at 10:21
  • I really just need a few variables passed, so it's an acceptable solution for me. Do you have a nicer idea that doesn't involve too much overhead? – slhck Apr 13 '12 at 11:53
  • @slhck: I'll think about it and let you know – klaffenboeck Apr 13 '12 at 16:01
1

You cannot have @map.title evaluated in a common js file, because that file is generated and served once, before later invokations of the controller, and then cached.

However, you can have javascript in your HTML page. That javascript can be generated with a constant value supplied by <%= @map.title %>.

Put the javascript in a partial, and render it in a tag in your page.

I have seen Bank of America do this in their web site. They generate all the account transactions in a javascript array on the page.

Marlin Pierce
  • 9,931
  • 4
  • 30
  • 52
0

Don't forget to use escape_javascript().

Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
alex
  • 1