Ruby on rails 如何在Rails循环中附加到nil对象? @preComments=Comment.where(:resource\u hash=>resource\u hash).排序(:created\u at.desc).全部 @预注释。每个do |注释| u=::User.find_by_id comment.User_id 普 @comments
使用Ruby on rails 如何在Rails循环中附加到nil对象? @preComments=Comment.where(:resource\u hash=>resource\u hash).排序(:created\u at.desc).全部 @预注释。每个do |注释| u=::User.find_by_id comment.User_id 普 @comments,ruby-on-rails,ruby-on-rails-3,object,iterator,Ruby On Rails,Ruby On Rails 3,Object,Iterator,使用@comments=[]在循环之前创建数组,然后在循环中确保使用@comments问题是,第一次迭代时,您希望创建@comments数组(包含该项),但随后的所有时间都希望将该项推送到现有数组上。也许有一种更优雅的方法可以做到这一点,但我通常只是这样做: @preComments = Comment.where(:resource_hash => resource_hash).sort(:created_at.desc).all @preComments.each do |co
@comments=[]
在循环之前创建数组,然后在循环中确保使用@comments问题是,第一次迭代时,您希望创建@comments数组(包含该项),但随后的所有时间都希望将该项推送到现有数组上。也许有一种更优雅的方法可以做到这一点,但我通常只是这样做:
@preComments = Comment.where(:resource_hash => resource_hash).sort(:created_at.desc).all
@preComments.each do |comment|
u = ::User.find_by_id comment.user_id
p u
@comments << @preComments
p "HERE!!!!!"
end
评论@comments=[comment]:@comments我认为您必须初始化数组
@comments ? @comments = [comment] : @comments << comment
我在下面回答了,但是如果您能更好地描述您试图通过@preComments
与@comments
实现的目标,可能有更好的方法。如果您先创建一个数组,您的视图为什么不能读取@comments?
@preComments = Comment.where(:resource_hash => resource_hash).sort(:created_at.desc).all
@comments = []
@preComments.each do |comment|
u = ::User.find_by_id comment.user_id
p u
@comments << comment
p "HERE!!!!!"
end
@preComments = Comment.where(:resource_hash => resource_hash).sort(:created_at.desc).all
@preComments.each do |comment|
u = ::User.find_by_id comment.user_id
p u
p "HERE!!!!!"
end
@comments = @preComments