Search code examples
ruby-on-railsmodel-view-controllersimple-formnested-formscocoon-gem

Cocoon nested form not showing in Rails 5


I have a model Recipe and a model Ingredient. Recipe has_many :ingredients, and Ingredient belongs_to :recipe. I'm using Cocoon and Simple Forms to create a nested form. The main form is working and showing, but for some reason the nested forms doesn't render. Any idea why?

Models

class Recipe < ApplicationRecord
    has_many :ingredients
end

class Ingredient < ApplicationRecord
    belongs_to :recipe
end

Recipes Controller (params)

    def recipe_params
        params.require(:recipe).permit(:title, :description, :image, 
        ingredients_attributes: [:id, :name, :_destroy], 
        directions_attributes: [:id, :step, :_destroy])
    end

View

<%= simple_form_for @recipe do |f| %>
    <div class="field">
        <h3>Recipe</h3>
        <%= f.input :title %>
        <%= f.input :description %>
        <%= f.input :image, as: :file %>

        <div id="ingredients">
            <h3>Ingredients</h3>

            <%= f.simple_fields_for :ingredients do |ingredient| %>
                    <p>ajsd</p>
                <%= render 'ingredients_fields', f: ingredient %>

                <%= link_to_add_associtation 'Add Ingredient', f, :ingredients %>
            <% end %>

        </div>

        <%= f.button :submit, class: "button button-highlight button-block" %>
    </div>
<% end %>

The simple_forms in the div#ingredients isn't rendering.


Solution

  • Your nested field form is displayed with this code:

    <%= f.simple_fields_for :ingredients do |ingredient| %>
      <p>ajsd</p>
      <%= render 'ingredients_fields', f: ingredient %>
      <%= link_to_add_associtation 'Add Ingredient', f, :ingredients %>
    <% end %>
    

    The code inside simple_fields_for is executed once for each ingredient in @recipe (and is not shown if @recipe does not have any ingredients).

    I guess you are creating an empty recipe. What you can do is add an empty ingredient to the recipe in the new method:

    @recipe.ingredients.build
    

    This will show an empty recipe in the form.

    Another important issue is that the link_to_add_association (which has a typo in your OP) is inside the simple_fields_for. It must be outside, so that it is shown at the end, and even if no ingredients are present.

    Finally, you are also missing:

    accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true