【问题标题】:Ruby on Rails : Cannot access an object's attributes in an arrayRuby on Rails:无法访问数组中对象的属性
【发布时间】:2009-07-31 16:10:09
【问题描述】:

我正在建立一个包含作品及其学分的网站。我正在努力实现的是根据他们的学分中的共同标题找到每个作品的相似作品。

我在 for 循环中将每个类似的作品添加到一个数组中,当我尝试访问这些作品的属性时,我得到一个 "nil object when you didn't expect it!" 错误.我在数组中调试时可以看到 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: {}

【问题讨论】:

    标签: ruby-on-rails arrays attributes object


    【解决方案1】:
    1. 变量为空,而不是其属性。
    2. 请粘贴整个堆栈
    3. 粘贴以下行的结果:
    4. 您的数组中可能有一个 nil 值。更正你的功能:

      def find_similar_works # .. 做你的事 # 然后删除 nil 值 @similar_works.compact! 结束

    【讨论】:

    • 非常感谢弗拉德。 @similar_work.compact!工作。你能解释一下为什么首先会出现这个问题吗?我错过了什么,或者不明白什么?谢谢
    • 不客气。这是因为这条线:'@similar_works
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2017-09-04
    相关资源
    最近更新 更多