A recipe has many ingredients and directions, each belongs to a recipe. My views/new.html.haml
renders a _form
partial, which renders the nested partials. It rejects upon submission saying that the required nested elements don't exist. I'm not sure what I'm doing wrong or missing. I've gone over the code and cocoon docs repeatedly. Any help would be greatly appreciated.
models/recipe.rb
has_many :ingredients
has_many :directions
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :directions, reject_if: :all_blank, allow_destroy: true
Using simple_form gem in a _form.html.haml
partial
%h3 Ingredients
#ingredients
= f.simple_fields_for :ingredients do |ingredient|
= render 'ingredient_fields', f: ingredient
.links
= link_to_add_association 'Add Ingredient', f, :ingredients
%h3 Directions
#directions
= f.simple_fields_for :directions do |direction|
= render 'direction_fields', f: direction
.links
= link_to_add_association 'Add Step', f, :directions
= f.button :submit
This links to a partial for each nested element, ingredients and directions...
views/recipes/_direction_fields.html.haml
.nested-fields
= f.input :step, input_html: { class: 'form-input form-control' }
= link_to_remove_association "Remove Step", f, class: 'btn btn-default form-button'
views/recipes/_ingredient_fields.html.haml
.nested-fields
= f.input :name, input_html: { class: "form-input form-control" }
= link_to_remove_association "Remove", f, class: "form-button btn btn-default"
When I attempt to submit a new recipe with directions and ingredients I get a rollback and flash notice reading...
2 Prevented this recipe from saving
Ingredients recipe must exist Directions recipe must exist
This solved my issue. cocoon gem attributes not saving when creating new recipe
Rails 5 now requires you to declare
inverse_of
in the model associations.