2012-01-17 72 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'達到VS'@ comments'什麼更好的說明,有可能是一個更好的辦法。 – 2012-01-17 19:14:56

+0

如果您先創建一個數組,請詳細說明爲什麼您的視圖無法讀取@comments? – 2012-01-17 20:14:30

回答

1

問題是您第一次迭代時,您想要創建@comments數組(包含該項目),但是您希望將該項目推送到現有數組的所有後續時間。有可能是一個更優雅的方式來做到這一點,但我一般只是這樣做:

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

使用@comments = []在循環之前創建數組,然後在循環中確保使用的是@comments << comment而不是@comments << @preComments

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