在我的主页我遍历对象的集合,并为每个对象我呈现其在表行的属性。有四个收藏的对象,在我的控制器定义为实例变量,所有制作卫队(根据所使用的方法)提高以下错误之一:
ActionView::Template::Error: undefined method `each_with_index' for nil:NilClass
ActionView::Template::Error: undefined method `any?' for nil:NilClass
在我的应用程序视图提高上述错误的代码是:
<table class="col-md-4 col-md-offset-1">
<thead>
<tr>
<th> Rank </th>
<th> Gamer </th>
<th> Points </th>
</tr>
</thead>
<tbody>
<% @atp_gamers.each_with_index do |gamer, index| %>
<tr>
<td class="index"> <%= index+1 %> </td>
<td class="gamer"> <%= gamer.name %> </td>
<td class="atppoints"> <%= gamer.atpscore %> </td>
</tr>
<% end %>
<tr class="current-user">
<td> <%= @atp_gamers.to_a.index(current_user) + 1 %> </td>
<td> <%= current_user.name %> </td>
<td> <%= current_user.atpscore %> </td>
</tr>
</tbody>
</table>
<table class="col-md-4 col-md-offset-2">
<thead>
<tr>
<th> Year </th>
<th> Champion </th>
<th> Points </th>
</tr>
</thead>
<tbody>
<% if @atp_champions.any? %>
<% @atp_champions.each do |champion| %>
<tr>
<td class="year"> <%= champion.created_at.year %> </td>
<td class="winnername"> <%= champion.name %> </td>
<td class="winnerpoints"> <%= champion.points %> </td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
上面的代码是在原来的主页上呈现的部分(名为_gamers_home.html.erb
)的一部分:
<% if logged_in? %>
<% if current_user.gamer? %>
<%= render 'static_pages/gamers_home' %>
<% else %>
<%= render 'static_pages/non_gamers_home' %>
<% end %>
<% else %>
<%= render 'static_pages/non_logged_in_home' %>
<% end %>
该logged_in?
方法被定义为!current_user.nil?
导致零实例变量是:@atp_gamers
,@wta_gamers
,@atp_champions
和@wta_champions
,在控制器定义如下:
def home
if logged_in? && !current_user.gamer?
...l
elsif logged_in? && current_user.gamer?
@gamers = User.where(gamer: true)
@atp_gamers = @gamers.order(atpscore: :desc).limit(50)
@wta_gamers = @gamers.order(wtascore: :desc).limit(50)
@atp_champions = AtpChampion.all
@wta_champions = WtaChampion.all
...
end
end
第一个实例变量提高误差(each_with_index' for nil:NilClass
)是@atp_gamers
。鉴于我试图与它的显式值来改变它,即User.where(gamer: true).order(atpscore: :desc).limit(50)
,和相应代码被接受。这一变化后,民警卫队提出了@atp_champions
错误。
随着轨道控制台@atp_gamers
和@wta_gamers
不为空,返回50条记录了100个用户。 @atp_champions
和@wta_champions
不是零,但空数组。
我怀疑这可能是只有卫队提出的一个问题,因为铁轨服务器在渲染视图成功。
def home
if logged_in? # delete this line
...
end # delete this line
end
删除if logged_in?
,看看会发生什么。
也许你在控制器使用before_action :logged_in_user, only :home
和定义logged_in_user
方法私有方法。
如果未注册用户也可以访问家里的动作,你需要使用if语句该局在视图中。喜欢,
<% if logged_in? %>
<% @atp_gamers.each_with_index do |gamer, index| %>
...
<% end %>
--UPDATE--
也许,它需要折腾变量部分。
更换
<%= render 'static_pages/gamers_home' %>
至
<%= render partial: 'static_pages/gamers_home', locals: {atg_gamers: @atp_gamers, wta_gamers: @wta_gamers, atp_champions: @atp_champions, wta_champions, @wta_champions} %>
并且,更换qazxsw POI,qazxsw POI,qazxsw POI,qazxsw POI在部分到@atp_gamers
,@wta_gamers
,@atp_champions
,@wta_champions
。
尝试,看看会发生什么。