[英]Ruby on Rails : Cannot access an object's attributes in an array
我正在建立一个包含作品及其功劳的网站。 我要达到的目的是根据作品的相互称号找到每件作品的相似作品。
我将每个类似的工作添加到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: {}
您的数组中可能有一个nil值。 更正您的功能:
def find_similar_works#..做您的工作#然后删除nil值@ similar_works.compact! 结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.