2015-07-20 114 views
0

我可能忽略了簡單的東西,但我仍然無法找到問題。簡單的未定義的方法錯誤 - 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 

感謝您的幫助!

回答

1

[].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 %> 
+0

它實際上是別的東西,我剛剛找到,但我並沒有考慮到這一點無論所以謝謝! – inthenameofmusik

0

試試這個:

<% 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 %> 
相關問題