2010-04-23 57 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