2010-06-22 38 views
0
Showing app/views/posts/_post.html.erb where line #4 raised: 

undefined method `name' for nil:NilClass 

Extracted source (around line #4): 

1: <p> 
2: <b>Post Content:</b> 
3: <%=h post.content %> by 
4: <%=h post.author.name %> 
5: </p> 

這裏是我的職位型號:爲無未定義的方法:NilClass但對象存在於控制檯

class Post < ActiveRecord::Base 
    belongs_to :board 
    belongs_to :author, :class_name => "User" 
end 

奇怪的是,如果我註釋掉post.author.name,它的工作原理。而且.... 我嘗試在控制檯,它工作正常:

>> post 
=> #<Post id: 1, content: "trying", user_id: 2, created_at: "2010-06-22 04:24:53", updated_at: "2010-06-22 04:24:53"> 
>> post.author 
=> #<User id: 2, login: "[email protected]", name: "test1",.... 
>> post.author.name 
=> "test1" 

事實上,如果我改變post.author.name到post.user_id,它會顯示正確的ID(即2) ....

什麼問題?

非常感謝。

+0

您能否顯示呈現_post.html的控制器操作方法?以及呈現它的視圖? – Pablo 2010-06-22 11:04:27

回答

0

兩件事情:

  1. 你確定你在控制檯檢查後是在視圖被訪問的同一個?也許你正在做類似post = Post.first這不是正確的嗎?
  2. 在提取的視圖源中,您引用了非實例變量。你是否在視圖的其他地方分配post(如循環)?如果不是,將其更改爲@post可能會這樣做。雖然這是不太可能的,因爲錯誤信息可能會有所不同。
+0

是的,這是我唯一的帖子,但我通過調用一個部分循環遍歷所有帖子。 >> Post.all => [#<帖子ID:1,內容:「正在嘗試」,user_id:2,created_at:「2010-06-22 04:24:53」,updated_at:「2010-06-22 4點24分53" 秒>] – user357203 2010-06-22 06:25:13

1

嘗試指定的值:foreign_key

0

你也必須指定:foreign_key => 「USER_ID」。默認情況下,Rails將使用傳遞給belongs_to的符號來派生外鍵字段。在你的情況下,即使你已經指定了類名,它會查找author_id作爲外鍵。 class_name選項告訴Rails需要什麼樣的對象。

相關問題