2009-07-31 88 views
0

我正在构建一个包含作品及其作品的网站。我努力实现的目标是根据他们的学分中的相互作品找出每件作品的类似作品。Ruby on Rails:无法访问数组中的对象属性

我在for循环中将每个类似的工作添加到数组中,当我试图访问这些作品的属性时,我得到一个“没有对象,当你不期待它!错误。我在数组中调试时可以看到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: {} 

回答

2
  1. 变量为空,而不是它的属性。
  2. 粘贴整个堆叠PLS
  3. 粘贴以下行的结果:<%=调试(work.similar_works)%>
  4. 是可能的有你的阵列中的零值。纠正你的函数:

    高清find_similar_works #..不要你的东西 #然后删除零值 @ similar_works.compact! end

+0

非常感谢vlad。 @ similar_work.compact!工作。 你能解释一下为什么会出现这个问题吗?我错过了什么,或者不明白? 谢谢 – fahrio 2009-07-31 20:41:23