Search code examples
ruby-on-railsruby-on-rails-4cocoon-gem

Rails nested forms select field default Value


I am having trouble displaying stored values in the select field of a nested form in Rails 4. I can create records using the nested form without a problem, but when I use the same form to edit the record, the details stored in the database are not being displayed in the select box.

I am able to display the value in the main form using the syntax below, I just do not know how to reference the values in the nested form.

This works in the main form:

<%= f.select :customer_id, options_for_select(Customer.all.collect {|c| [ c.name, c.id ] }, @estimate.customer_id), {}, { :class => 'form-control'} %>

Here is the relevant nested parts of my view.

<%= 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 %>

I have tried using ff.area_id and a bunch of other variations but I get an "undefined method ..." error with every one that I try.

I'm using Rails 4.2.4 with the Cocoon gem for dynamic nesting.


Solution

  • You can get the object of the subform and use that:

    ff.object.area_id