问题
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 thejs.erb
file? - How else can I access this instance variable defined in my controller?
回答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 %>
回答2:
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.
回答3:
Don't forget to use escape_javascript()
.
来源:https://stackoverflow.com/questions/10131208/nomethoderror-thrown-when-trying-to-use-controller-variables-in-js-erb-file