我在Rails 4中的嵌套表单的选择字段中显示存储的值时遇到问题。我可以使用嵌套表单创建记录而没有问题,但是当我使用相同的表单编辑记录时,存储在数据库中的详细信息是没有显示在选择框中。
我可以使用下面的语法在主窗体中显示值,我只是不知道如何引用嵌套窗体中的值。
这适用于主要形式:
<%= f.select :customer_id, options_for_select(Customer.all.collect {|c| [ c.name, c.id ] }, @estimate.customer_id), {}, { :class => 'form-control'} %>
这是我视图的相关嵌套部分。
<%= form_for @estimate, html: { class: "form-horizontal form-label-left" } do |f| %>
...
<%= f.fields_for :estimate_details do |ff| %>
<tr class="details_row nested-fields">
<td><%= ff.select :area_id, options_for_select(Area.all.collect {|c| [ c.area_name, c.id ] }), {include_blank: true}, { :class => 'form-control'} %></td>
<td><%= ff.select :product_id, options_for_select(Product.select(:product_number, :id).where(:active => 't').map {|c| [ c.product_number, c.id ] }), {include_blank: true}, { :class => 'form-control'} %></td>
<td><%= ff.number_field :quantity, class: 'form-control', "min" => 1 %></td>
<td><%= ff.select :accessory_id, options_for_select(Product.select(:product_number, :id).where(:accessory => 't', :active => 't').map {|c| [ c.product_number, c.id ] }), {include_blank: true}, { :class => 'form-control'} %></td>
<td><%= ff.text_field :notes, class: 'form-control' %></td>
<td><%= link_to_remove_association '<i class="fa fa-trash"></i>'.html_safe, f %></td>
</tr>
<% end %>
<% end %>
我已经尝试过使用ff.area_id和其他一些变体,但是每次尝试都会出现“未定义的方法......”错误。
我正在使用Rails 4.2.4和Cocoon gem进行动态嵌套。
您可以获取子表单的对象并使用它:
ff.object.area_id
<td>
<%= ff.select :area_id, options_for_select(Area.all.collect {|c| [ c.area_name, c.id ], ff.object.area_id }), {include_blank: true}, { :class => 'form-control'} %>
</td>