2011-03-24 33 views
0
NoMethodError in Points#create 

Showing /Volumes/EXTERNAL/Proiecte/Roadie/app/views/points/_form.html.erb where line #20 raised: 

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.collect 
Extracted source (around line #20): 

17: </div> 
18: <div class="field"> 
19:  <%= f.label :section %><br /> 
20:  <%= f.select(:section_id, [["Select a Section name", 0]] + @sections.collect {|p| [ p.name, p.id ] }) %> 
21: </div> 
22: 
23: <div class="field"> 

基本上這裏發生的是,當這個表單頁面中的其他字段中的一個(通過模型驗證)丟失時,rails會將上面發佈的錯誤排除。Rails error at validate_presence_of

一個部分有很多點,當創建一個新的點時,用戶應該能夠選擇一個父節。

任何人都可以解釋爲什麼會發生這種情況?

回答

3

發生這種情況是因爲@sections實例變量爲零。以下是我猜測正在發生的事情根據您的文章:

您提交表單與不完整的數據,要創建的帖子。該模型未保存,因此您重新呈現「新」動作。但是,您忘記在控制器的「新建」操作中重新初始化變量。

在Rails中,當您調用render(:action =>'new')時,它不會執行控制器的'new'方法中的代碼。它只是呈現'新'模板,所以你仍然需要設置任何實例變量。

+0

那麼我將如何去重新初始化新動作中的變量? – Carvefx 2011-03-24 13:23:01

+0

最後,我將@sections修改爲Section.all – Carvefx 2011-03-24 13:37:44

+0

通常您可以在呈現動作之前再次調用'new',或者在控制器中編寫一個輔助方法,爲您的'new'和'''''創建'行動。 – npj 2011-03-24 15:22:26