0

當我執行命令有很多評論此錯誤時顯示的用戶列:獲取的has_many的在軌誤差(無法誤差)值

 <% post.comments.each do |comment| %> 
     <div id="comments" > 
      <%= comment.user.email if comment.user.email != nil %> 
       <%= comment.comment %> 
     </div> 
NoMethodError in Posts#index 

Showing /Users/overallduka/Blog1/app/views/posts/index.html.erb where line #50 raised: 

undefined method `email' for nil:NilClass 
Extracted source (around line #50): 

的意見模型有belongs_to的用戶和用戶模型has_many評論,因爲這個,但我沒有找到問題,我檢查和所有我的意見有user_id,請一些解決方案,請。

+0

你提到您的所有意見都自己USER_ID定義的,但你確定它們都是有效的用戶ID?即可能評論具有不再存在的用戶的user_id。只有一種可能性。 –

回答

1

問題是您的post對象上的至少一個comments對於user關聯具有nil值。你檢查email不是零,但你不檢查自身是否user是零(這是什麼觸發了NoMethodError)。

作爲開始,我會改變這一行:

<%= comment.user.email if comment.user.email != nil %> 

到:

<%= comment.user && comment.user.email %> 

這是紅寶石一個方便的圖案首先檢查comment.user定義其中,並且如果它被定義返回第二個參數,即comment.user.email。如果comment.user沒有定義(或nil,或false),那麼第二個參數不評估,並返回值是零(所以如果沒有用戶定義,然後comment.user.email不會求這樣你就不會得到一個錯誤)。

+0

非常感謝謝謝 – overallduka