尝试在js.erb文件中使用控制器变量时抛出NoMethodError [英] NoMethodError thrown when trying to use controller variables in js.erb file
问题描述
在我的资产中,我有一个名为 maps.js.erb
的文件,基本上只有以下(调试)内容:
In my assets, I have a file called maps.js.erb
, basically with only the following (debugging) content:
alert("<%= @map.width %>");
这个JS文件是通过 show.html.erb $加载的c $ c>属于地图的视图。
This JS file is loaded through the show.html.erb
view belonging to maps.
<%= javascript_include_tag params[:controller] %>
<h1><%= @map.title %></h1>
…
HTML文件本身显示地图的标题,例如:浏览 / maps / 1 /
时,由于 @map
在控制器中定义。但是,只要我包含JS文件,就会出现以下错误:
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#show
显示
... / app / views / maps / show.html.erb
第1行引发的地方:
NoMethodError in Maps#show
Showing
…/app/views/maps/show.html.erb
where line #1 raised:
nil的未定义方法'title':NilClass
(在 ... / app / assets / javascripts / maps.js.erb
)
undefined method 'title' for nil:NilClass
(in …/app/assets/javascripts/maps.js.erb
)
- 为什么
@map
在js.erb
档案? - 我还能如何访问我的控制器中定义的这个实例变量?
- Why is
@map
not available in thejs.erb
file? - How else can I access this instance variable defined in my controller?
推荐答案
Ryan Bates就该主题做了一个截屏视频 - 你可能想看一下:
Ryan Bates did a screencast right on that topic - you might wanna check it out:
http://railscasts.com/episodes/324-passing-data-to-javascript
在 html.erb
文件中,您可以定义变量:
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 %>
这篇关于尝试在js.erb文件中使用控制器变量时抛出NoMethodError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!