2012-01-17 9 views
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 

私のコードですが、@commentsが、私はエラーを取得するように定義されていません。Railsでループを繰り返すnilオブジェクトに追加するには?

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.<<

私は最初の配列を作成した場合、その後、私の見解は、それを読み取ることができませんが。だから私はこれをどうやってやるの?

+0

私は以下のように答えましたが、あなたが '@ preComments'と' @ comments'を使って達成しようとしていることのより良い記述をした方がよいでしょう。 –

+0

配列を最初に作成すると、ビューで@commentsを読み取ることができない理由を詳細にお知らせください。 –

答えて

1

問題は、初めて反復するときに、(その項目を含む)@comments配列を作成したいが、その項目を既存の配列にプッシュしたいということです。そこにこれを行うには、よりエレガントな方法は、おそらくですが、私は一般的にちょうどこの操作を行います。

@comments ? @comments = [comment] : @comments << comment 
0

@comments = []を使用してループの前に配列を作成し、ループ内で@comments << @preCommentsではなく@comments << commentを使用していることを確認してください。

0

を、私はあなたが、配列初期化しなければならないと思います

@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の値を渡しますコメント

@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 
関連する問題