好的,我是新手,但是尝试学习一下,如果这个问题暴露了我的知识不足,我深表歉意!
我有一个非常简单的应用程序,具有2个模型(构建和定制)和2个控制器(构建和定制),每个模型都有一个索引视图。
我的根源是建筑物#index
在buildings#index视图中,我尝试按照以下方式从两个模型访问数据:
<div class="wrap">
<header>
<% @setup.each do |customise| %>
<h1><%= customise.title %></h1>
<% end %>
我在建筑物控制器中的哪个位置定义了:
def index
@buildings = Building.all
@unis = Building.where(buildingtype: "uni")
if params[:parentd].present?
@buildings = Building.where("university = ? OR buildingtype = 'directlet'", params[:parentd])
@setup = Customise.all
end
这将产生以下错误:
ActionView::Template::Error (undefined method `each' for nil:NilClass):
4:
5: <% end %>
6:
7: <% @unis.each do |uni| %>
8: <option value="<%= uni.name %>"><%= uni.name %></option>
9: <% end %>
app/views/customises/index.html.erb:7:in
`_app_views_customises_index_html_erb__589235851577785880_2190604320'
我的阅读表明,可以从任何视图访问两个模型的数据,这使我相信我的表示法有问题。
但是,当我尝试以相同的方式但在与定制控制器关联的视图中访问相同的模型信息时,数据显示没有错误。
有人可以提出这个背后的原因吗?
在您的控制器中,如果条件未得到满足,@setup
则也是如此nil
。确保@setup
被初始化。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句