0
  @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

That's my code, but @comments isn't defined so I get an error:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.<<

If I create an array first, then my view can't read it. So how do I do this?

2
  • I answered below, but if you give a better description of what you're trying to achieve with @preComments vs @comments, there might be a better way. Commented Jan 17, 2012 at 19:14
  • Could you please give more detail why your view can't read @comments if you create an array first ? Commented Jan 17, 2012 at 20:14

3 Answers 3

1

The problem is that the first time you iterate, you want to create the @comments array (containing that item), but all subsequent times you want to push that item onto the existing array. There's probably a more elegant way to do this, but I generally just do this:

@comments ? @comments = [comment] : @comments << comment
Sign up to request clarification or add additional context in comments.

Comments

0

Create the array before the loop using @comments = [], then in the loop make sure you're using @comments << comment, not @comments << @preComments.

Comments

0

I think you must initialize array

@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

or when loop is finished then pass values of @preComments to @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
  p "HERE!!!!!"
end
@comments = @preComments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.