简单的未定义方法错误 - Rails
Simple Undefined Method Error - Rails
我可能忽略了一些简单的东西,但我仍然没能找到问题所在。
控制器:
(第一行是一个很长的 Thinking Sphinx 查询)
@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
即您的查询 returns 没有结果。在遍历它们之前,只需检查 @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 %>
我可能忽略了一些简单的东西,但我仍然没能找到问题所在。
控制器: (第一行是一个很长的 Thinking Sphinx 查询)
@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
即您的查询 returns 没有结果。在遍历它们之前,只需检查 @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 %>