【问题标题】:Simple Undefined Method Error - Rails简单的未定义方法错误 - Rails
【发布时间】:2015-10-09 12:46:19
【问题描述】:

我可能在这里忽略了一些简单的事情,但我仍然无法找到问题。

控制器: (第一行是一个很长的 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

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails null each instance-variables enumerable


    【解决方案1】:

    试试这个:

    <% 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 %>
    

    【讨论】:

      【解决方案2】:

      [].last =&gt; 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 %>
      

      【讨论】:

      • 这实际上是我刚刚发现的其他东西,但我也没有考虑到这一点,所以谢谢!
      猜你喜欢
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多