2012-01-17 2 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은 내가 오류가 그렇게 정의되지 않은 : 내가 먼저 배열을 만들 경우루프를 통해 루프를 반복하면서 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의 값을 전달 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 
관련 문제