我在rails视图中有一个嵌套的表单,就像这样调用
<% 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
,则错误消息变为undefined local variable or method
item_number'#instead. The invoice_item_number object that is being displayed by this partial is being used perfectly well by the form helpers as
&lt;%= f.text_field:item_number% &gt; and
&lt;%f.text_field:amount%&gt; both work perfectly well. I have tried a number of solutions such as using
@ invoice_item_number`并在render方法中明确定义了一个对象,但这些都没有用。
大概有一个非常简单的答案。
答案 0 :(得分:6)
重新阅读Ryan在http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes的嵌套表格上的帖子,并找到答案。它已经在我的代码中,但我不明白发生了什么。我可以使用f.object访问invoice_item_number对象,因此用<%= invoice_item_number.description %>
替换<%= f.object.description %>
解决了我的问题。
答案 1 :(得分:2)
如何改变:
<%= invoice_item_number.description %>
到
<%= f.label :description %>
或者如果您需要字段:
<%= f.text_field :description %>