nathanvda/cocoon

How to add association for 2 fields at the same time

lo-bi opened this issue · 2 comments

lo-bi commented

Hi,

When clicking on "Add field", I would like to display the select (called perimeter field) + the input value.
It works well when loading the page for the first row but when I click on "Add field", it only loads the perimeter field select. Can someone help me?

Thanks

Screenshot 2020-03-27 at 17 07 30

_form.html.erb

    <%= f.simple_fields_for :perimeter_field do |perimeter_field| %>
        <%= render 'perimeter_field_fields', f: perimeter_field %>
    <% end %>
    <div>
      <%= link_to_add_association 'Add Field', f, :perimeter_field, class: 'btn btn-success' %>
    </div>

_perimeter_field_fields.html.erb

<div class="nested-fields form-row">
    <div class="form-group form-row col-md-8">
        <%= f.select :field_id, @field.collect{|s|[s.name,s.id]}, class: 'form-control col-sm-6' %>
        <%= f.simple_fields_for :perimeter_field_value do |perimeter_field_value_field| %>
            <%= render 'perimeter_field_value_fields', f: perimeter_field_value_field %>
        <% end %>
        
    </div>
    <div class="form-group col-md-4">
        <%= link_to_remove_association 'Remove Field', f, class: 'btn btn-warning' %>
    </div>
</div>

_perimeter_field_value_fields.html.erb

<%= f.input :value, label: false, class: 'form-control col-sm-6' %>

So do I understand correctly that your main object has many -> perimeter_fields, which then has many -> perimeter_field_values, and that this relation is not created when clicking on the add field link?

Check: #557

lo-bi commented

I have added wrap_object like this:

<%= link_to_add_association 'Add Field', f, :perimeter_field, class: 'btn btn-success', wrap_object: Proc.new { |perimeter_build| perimeter_build.perimeter_field_value.build; perimeter_build }  %>

Then it works perfectly! Thank you very much