2011-04-19 76 views
1

我正在嘗試修復向評論表添加列並執行一些更新的一些問題。但有一整天此錯誤:在Rails移植中使用模型關聯的問題

rake aborted! An error has occurred, all later migrations canceled:

You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]

遷移代碼:

class AddCommenterNameToComments < ActiveRecord::Migration 
    def self.up 
    add_column :comments, :commenter_name, :string 
    Comment.reset_column_information 

    #to update all comments with commenter name 
    Comment.all.each do |comment| 
     unless comment.is_system_message? 
      comment.update_attribute(:commenter_name, comment.user.name) 
     end 
    end 
    end 

    def self.down 
    remove_column :comments, :commenter_name 
    end 
end 

請幫助。

回答

0

該關聯可能不是問題,而是測試它是否可以通過從註釋表中傳入user_id列來搜索用戶對象。因此,舉例來說: 編輯與OP建議修復

class AddCommenterNameToComments < ActiveRecord::Migration 
    class Comment < ActiveRecord::Base 
    end 
    class User < ActiveRecord::Base 
    end 
    def self.up 
    add_column :comments, :commenter_name, :string 
    Comment.reset_column_information 

    #to update all comments with commenter name 
    Comment.all.each do |comment| 
     unless comment.is_system_message? 
     user = User.find_by_id(comment.user_id) 
     if user 
      comment.update_attribute(:commenter_name, user.name) 
     else 
      comment.update_attribute(:commenter_name, "User deleted") 
     end 
     end 
    end 
    end 

    def self.down 
    remove_column :comments, :commenter_name 
    end 
end 

現在說,這個問題可能是你在意見表不再對應於用戶表用戶對象爲user_id。你可能也想檢查一下,以防結果不成問題。

+0

嗨威利安,其實,爲了簡單起見,我已經從代碼中刪除了這個驗證。我原來有: 'Comment.all.each do | comment | 除非comment.is_system_message? 如果comment.user comment.update_attribute(:COMMENTER_NAME,comment.user.name) 別的 comment.update_attribute(:COMMENTER_NAME, 「用戶已刪除」) 端 端 end' 從來就也改變與User.find_by_id,但仍然發生錯誤。 – Valadares 2011-04-19 20:46:12

+0

它給出了任何行號? – William 2011-04-19 20:50:29

+0

此外,雖然它會導致大量輸出,但可以嘗試在每個循環中放置一個'p comment.inspect'或其他東西,以查看哪些註釋對象出錯。 – William 2011-04-19 20:55:15