我正在建立一个有作品及其学分的网站。我想要实现的是根据其学分中的共同标题找到每件作品的类似作品。
我将每个类似的工作添加到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: {}
答案 0 :(得分:2)
您的数组中可能有一个nil值。纠正你的功能:
def find_similar_works #..做你的东西 #然后删除nil值 @ similar_works.compact! 端