bra*_*rad 2 forms ruby-on-rails partial-views nested-forms
我在rails视图中有一个嵌套的表单,就像这样调用
<% f.fields_for :invoice_item_numbers do |item_no_form| %>
<%= render 'invoice_item_number', :f => item_no_form %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
部分(_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>
Run Code Online (Sandbox Code Playgroud)
这失败并显示错误消息
undefined method `description' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
为什么invoice_item_number在此部分中返回nil对象?它显然是以某种方式定义的,因为如果我将其更改为其他内容(例如,item_number.description然后错误消息变为undefined local variable or methoditem_number'用于#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`并明确定义render方法中的一个对象,但这些对象没有用.
据推测,有一个非常简单的答案.
只需在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 %>解决的问题.
| 归档时间: |
|
| 查看次数: |
2352 次 |
| 最近记录: |