简单的未定义方法错误- Rails



我可能在这里忽略了一些简单的东西,但我仍然没有能够找到问题。

控制器:(第一行是一个很长的思芬克斯查询)

@artwork_q = Artwork.search params[:q], :conditions => {:subject => params[:artwork][:subject_ids], :location => params[:artwork][:location_ids], :artist_last => params[:artwork][:artist_id], :artist_first => params[:artwork][:artist_id]}, :order => params[:sort][:title]
@last_artwork = Artwork.new
@last_artwork = @artwork_q.last
render 'index2'

视图:

<% @artwork_q.each.with_index do |art, index| %>
    <div class="a-result<%= " last-one" if art.id == @last_artwork.id %>" id="<%= index %>">
<% end %>

我测试了art.id,工作正常。是@last_artwork.id引发了这个错误也就是

NoMethodError in Artworks#index2
Showing /Users/<user>/Developer/<project>/<rails_root>/app/views/artworks/index2.html.erb where line #49 raised:
undefined method `id' for nil:NilClass

谢谢你的帮助!

[].last => nil即您的查询没有返回结果。在循环之前,只需检查@artwork_q是否有一些结果。

<% unless @artwork_q.blank? %>
  <% @artwork_q.each.with_index do |art, index| %>
    <div class="a-result<%= " last-one" if art.id == @last_artwork.id %>" id="<%= index %>">
  <% end %>
<% end %>

试试这个:

<% unless @artwork_q.blank? %>
  <% @artwork_q.each.with_index do |art, index| %>
    <% unless @last_artwork.blank? %>
      <div class="a-result<%= " last-one" if art.id == @last_artwork.id %>" id="<%= index %>">
      <% end %>
  <% end %>
<% end %>

最新更新