Search code examples
ruby-on-railsnested-formscocoon-gem

How to pre-populate nested fields with existing data in Rails?


I have Receipt model which has many ingredients. So, I use

gem "nested_form"
gem "cocoon"

for nested forms. Everything goes well while creating a new ingredient (or a few ingredients). But I want to pre-fill this fields with existing data while editing.

_form.html.slim

= f.fields_for :ingredients, [@receipt.ingredients.build] do |i|
    = render 'ingredient_fields', f: i
    = link_to_add_association 'Add ingredient', f, :ingredients, class: "btn btn-success"
  br/

_ingredient_fields.html.slim

.nested-fields
  .row
    .form-group.col-xs-5
      .field        
        = f.text_field :name, placeholder: "Name", class: "form-control"
    .form-group.col-xs-3
      .field
        = f.number_field :count, placeholder: "Count", class: "form-control"
    .form-group.col-xs-3    
      .field
        = f.select :count_name, [['gr', 'gr'], ['kg', 'kg']], placeholder: "count name", class: "form-control"
    = link_to_remove_association image_tag("/close.png"), f

This is part of the receipts controller

def edit
    @ingredients = @receipt.ingredients
end

Solution

  • In your form you should write:

    = f.fields_for :ingredients do |i|
    

    This will iterate over the existing ingredients for a receipt. If you still want to add a new ingredient by default when creating a new receipt, you can do this simplest as follows in your receipts_controller:

    def new
      @receipt = Receipt.new
      @receipt.ingredients.build
    end