Rails 嵌套表单 select 字段默认值

Rails nested forms select field default Value

我无法在 Rails 中的嵌套表单的 select 字段中显示存储值 4. 我可以使用嵌套表单毫无问题地创建记录,但是当我使用相同的表单时表单编辑记录,存储在数据库中的详细信息未显示在 select 框中。

我可以使用下面的语法在主窗体中显示值,我只是不知道如何在嵌套窗体中引用值。

这在主要形式中有效:

<%= 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 和其他一些变体,但我尝试的每一个变体都出现 "undefined method ..." 错误。

我正在使用 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>