Nil对象何时没想到它

时间:2013-05-14 14:53:36

标签: ruby-on-rails ruby

Legacy Ruby on Rails 2.3项目在这里。得到以下错误:

You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]

提取的来源(第122行):

119: <%= link_to 'Printable', { :action => 'print', :id => @incident.id }, { :target => '_blank', :class => "button" } %>
120: <% if isviewable?(@incident) %>
121: 
122:   <%= link_to "Pictures (#{@incident.pictures.count})", incident_pictures_path(@incident), :class => "button" %>
123:   <%= link_to "Suspects (#{@incident.suspects.count})", incident_suspects_path(@incident), :class => "button" %>
124:   <%= link_to "Notes (#{@incident.notes.count})", incident_notes_path(@incident), :class => "button"%>
125:   <%= link_to "Cars (#{@incident.cars.count})", incident_cars_path(@incident), :class => "button" %>

任何想法?感谢。

编辑:删除第122行修复了异常,但如果该记录有一个,我可能需要显示一张图片,所以我不能仅仅取出该功能。

编辑2:应用程序跟踪下的异常页面中还有这一行:

/usr/local/rvm/gems/ruby-1.8.7-p371/gems/paperclip-2.3.0/lib/paperclip.rb:303:in `validates_attachment_content_type'

我的回形针插件可能是错误吗?

2 个答案:

答案 0 :(得分:0)

119: <%= link_to 'Printable', { :action => 'print', :id => @incident.id }, { :target => '_blank', :class => "button" } %>
    <% if @incident.present?%>       #### you need to check for null object. ######
120: <% if isviewable?(@incident) %>
121:
122:   <%= link_to "Pictures (#{@incident.pictures.count})", incident_pictures_path(@incident), :class => "button" %>
123:   <%= link_to "Suspects (#{@incident.suspects.count})", incident_suspects_path(@incident), :class => "button" %>
124:   <%= link_to "Notes (#{@incident.notes.count})", incident_notes_path(@incident), :class => "button"%>
125:   <%= link_to "Cars (#{@incident.cars.count})", incident_cars_path(@incident), :class => "button" %>

你需要检查空对象,然后它会很好地工作。

答案 1 :(得分:0)

尝试在控制器中使用.find_by_id而不是.find。然后你可以在继续之前检查结果(@ incident.nil?)。

编辑:

@incident.pictures?如何查看是否有?