Ruby You might have expected an instance of Array 的时候的屏蔽方法

sunsonavaj · April 25, 2012 · Last by yakjuly replied at April 27, 2012 · 2922 hits

You might have expected an instance of Array. The error occurred while evaluating nil.each_with_index) on line #42 of <% @c.each_with_index do |c, index| %> #donothing <%end%> controller 中@c为查询语句 因为数据为空! 这样的话该这样屏蔽掉这个错误呢。因为现在是部署项目不能让用户看到这个错误,因为一旦有数据就不会出现错误的。

<% Array(@c).each_with_index do |c, index| %> 
  #donothing
<%end%>

PS. RubyChina 快成了问答网站了..

#1 楼 @hooopo 应该是大量新用户涌入的结果吧

给一个判断, 方法 1:

if <%@c%> <% @c.each_with_index do |c, index| %> #donothing <%end%> end

方法二: 在 controller 里面取"@c"的时候给一个默认数据例如:

@c = @c.nil? ? : [] : @c 或者 @c ||= []

我们以前项目里有很多这样的东西 <% @c && @c.each_with_index do |c, index| %>

#5 楼 @hooopo 也可以这样

<% @c.try(:each_with_index) do |c, index| %>
  #do sth
<% end %>

最好的办法就是在 each_with_index 之前 在 controller 里就确保 c 实例变量是一个数组。不要在遍历的时候才把它兼容成数组。

You need to Sign in before reply, if you don't have an account, please Sign up first.