2010-04-23 38 views
2

我已經在軌道嵌套表格視圖被稱爲像這樣問題在嵌套形式局部存取變量

<% f.fields_for :invoice_item_numbers do |item_no_form| %> 
    <%= render 'invoice_item_number', :f => item_no_form %> 
<% end %> 

和部分(_invoice_item_number.html.erb)看起來像這樣

<div class='invoice_item_numbers'> 
<% if f.object.new_record? %> 
     <li><%= f.label :item_number %><%= f.text_field :item_number %> 
    <%= link_to_function "remove", "$(this).parent().remove()", :class => 'remove_link' %></li> 
<% else %> 
    <li class="inline"><%= f.label :item_number %><%= f.text_field :item_number %> 
    </li><li class="inline"><%= f.label :description %><%= invoice_item_number.description %></li><li><%= f.label :amount %><%= f.text_field :amount %> 
    <%= f.check_box '_destroy', :class => 'remove_checkbox' %> 
    <%= f.label '_destroy', 'remove', :class => 'remove_label' %></li> 
<% end %> 
</div> 

這種失敗,出現錯誤消息

undefined method `description' for nil:NilClass 

爲什麼invoice_item_number在這部分返回nil對象?這顯然是被莫名其妙地定義,因爲如果我將其更改爲別的東西(如item_number.description則錯誤消息成爲ITEM_NUMBER undefined local variable or method」爲#instead. The invoice_item_number object that is being displayed by this partial is being used perfectly well by the form helpers as <%= f.text_field:%ITEM_NUMBER>and <%f.text_field:數量%>both work perfectly well. I have tried a number of solutions such as using @ invoice_item_number`和顯式定義的渲染方法的對象,但這些都沒有奏效

大概有一個很簡單的答案,這

回答

6

只是重新閱讀瑞安的碎片對嵌套形式張貼在http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes並找到了答案。它已經在我的代碼中,但我不明白髮生了什麼。我可以使用f.object訪問invoice_item_number對象,因此用<%= f.object.description %>代替<%= invoice_item_number.description %>解決了我的問題。

+0

甜。 (我誤解了你的問題,對不起;-) – ohho 2010-04-23 09:21:48

+0

沒問題。我很感激你花時間閱讀它。謝謝。 – brad 2010-04-23 10:43:50

+1

是我還是大多數名爲Ryan的'着名'rails開發人員? Ryan Bigg,Ryan Bates,Ryan Daigle .. wtf haha​​h – imjp 2011-07-29 13:20:51

2

怎麼樣改變:。

<%= invoice_item_number.description %> 

<%= f.label :description %> 

,或者如果你需要一個字段:

<%= f.text_field :description %> 
+0

嗯,我已經有f.label:在那裏的描述。有趣的是,如果我確實輸入了f.text_field:description,就可以完全按照我的意願訪問描述方法,但我不想要文本字段,我只想要文本。不過謝謝。 – brad 2010-04-23 06:56:20

+0

invoice_item_number在部分中爲零(尚未定義)。如果要訪問模型數據,則需要在控制器中定義@invoice_item_number,並通過@ invoice_item_number.description – ohho 2010-04-23 07:15:55

+0

進行訪問嗯,但在此情況下,invoice_item_number是嵌套屬性。父級屬性(發票)在控制器中用@ invoice = Invoice.find(params [:id])定義。我真正想訪問的是invoice.invoice_item_number.description,但我不知道如何在我的部分。 – brad 2010-04-23 08:46:23