Ruby on Rails:无法访问数组中对象的属性

时间:2009-07-31 16:10:10

标签: ruby-on-rails arrays attributes object

我正在建立一个有作品及其学分的网站。我想要实现的是根据其学分中的共同标题找到每件作品的类似作品。

我将每个类似的工作添加到for循环中的数组中,当我尝试访问这些工作的属性时,我得到一个“nil对象,当你没想到它时!”错误。我在数组中调试时可以看到Work对象,但是无法访问它们的属性。这是代码:

class Work < ActiveRecord::Base

  def similar_works
    @similar_works
  end

  def find_similar_works
    @similar_works = []
    for credit in self.credits
      same_credits = credit.title.credits #same credits with mutual titles
      for credit2 in same_credits
        @similar_works << credit2.work
        end
    end
  end

end



class WorksController < ApplicationController

  def index
    list
    render(:action => 'list')
  end

  def list
    # find similar works for each work
    @works.each do |work|
      work.find_similar_works
    end
  end

end



list.html

<% for work in @works -%>
<% for similarwork in work.similar_works%>
    <%= similarwork.name%> => nil object
    <%=debug(similarwork)%> => sample debug output is below
<% end %>
<% end %>



--- !ruby/object:Work 
attributes: 
  name: Borozan
  updated_at: 2009-07-31 12:30:30
  created_at: 2009-07-31 12:25:32
attributes_cache: {}

--- !ruby/object:Work 
attributes: 
  name: Boom
  updated_at: 2009-07-31 12:30:30
  created_at: 2009-07-31 12:25:32
attributes_cache: {}

--- !ruby/object:Work 
attributes: 
  name: Kamuflaj
  updated_at: 2009-07-31 12:30:30
  created_at: 2009-07-31 12:25:32
attributes_cache: {}

1 个答案:

答案 0 :(得分:2)

  1. 变量为null,而不是其属性。
  2. 粘贴整个堆栈
  3. 粘贴以下行的结果:&lt;%= debug(work.similar_works)%&gt;
  4. 您的数组中可能有一个nil值。纠正你的功能:

    def find_similar_works   #..做你的东西   #然后删除nil值   @ similar_works.compact! 端