nathanvda / cocoon

Dynamic nested forms using jQuery made easy; works with formtastic, simple_form or default forms
http://github.com/nathanvda/cocoon
MIT License
3.08k stars 383 forks source link

For some reason my cocoon form is not showing already existing records for nested field in edit form. #606

Closed ratnamyadav closed 3 years ago

ratnamyadav commented 3 years ago

Everything is working fine but I am not seeing already existing records in prices for Cake in cocoon form. So I am unable to edit / delete existing records but able to add new prices from edit form.

class Cake < ApplicationRecord
  has_many :prices, as: :item

  accepts_nested_attributes_for :prices, reject_if: :all_blank, allow_destroy: true
end
class Price < ApplicationRecord
  belongs_to :item, polymorphic: true
  belongs_to :size

  has_and_belongs_to_many :shapes
end
<%= form_with(model: cake, url: cake.id? ? crm_cake_path(cake) : crm_cakes_path, html: { novalidate: true }) do |form| %>
  <div id="prices">
    <% form.fields_for :prices do |price| %>
      <%= render 'price_fields', f: price %>
    <% end %>
    <div class="links mt-2">
      <%= link_to_add_association 'Add Price', form, :prices, class: 'btn btn-info' %>
    </div>
  </div>
<% end %>
<div class="nested-fields">
  <div class="row mb-1">
    <div class="col-md-4">
      <%= f.label :size_id %>
      <%= f.select :size_id, options_for_select(Size.order(:id).map { |s| [s.name, s.id] }, f.object.size_id), {},
                   class: 'form-control' %>
    </div>
    <div class="col-md-4">
      <%= f.label :additional_text, 'Servings' %>
      <%= f.text_field :additional_text, class: 'form-control' %>
    </div>
    <div class="col-md-4">
      <%= f.label :price %>
      <%= f.number_field :price, class: 'form-control' %>
    </div>
  </div>
  <%= link_to_remove_association "Remove Price", f, class: 'btn btn-danger' %>
</div>
nathanvda commented 3 years ago

This is a classic mistake/typo: you forgot the = before the fields_for.

So the corrected line should look like

<%= form.fields_for :prices do |price| %>
ratnamyadav commented 3 years ago

Silly me thanks @nathanvda