2

我在 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 methoditem_number' for # 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 :amount %> both work perfectly well. I have tried a number of solutions such as using@invoice_item_number` 并明确定义渲染方法中的一个对象,但这些都不起作用。

大概有一个非常简单的答案。

4

2 回答 2

6

只需在http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes上重新阅读 Ryan 的关于嵌套表单的文章,并找到答案。它已经在我的代码中,但我不明白发生了什么。我可以使用 f.object 访问 invoice_item_number 对象,因此替换<%= invoice_item_number.description %><%= f.object.description %>解决了我的问题。

于 2010-04-23T09:04:15.010 回答
2

如何改变:

<%= invoice_item_number.description %>

<%= f.label :description %>

或者如果您需要一个字段:

<%= f.text_field :description %>
于 2010-04-23T06:32:33.347 回答