1
votes

I'm building a recipe app, where a user has the option of choosing pre existing ingredients and if the ingredient can't be found an option for the user to note down ingredient name on a input field. I want the form to have up to 5 input fields.

Iv seen similar questions asked but their solution has not worked. q1

q2

Here's what I got so far, I'v tried two ways of doing it.

<%=f.fields_for :ingredients do |ing|%>
    <%= ing.label :name, "Enter ingredient name"%>
    <br>
    <%= ing.text_field :name%>
 <%end%>

 <%=f.fields_for :recipe_ingredients do |ri|%>
    <%=ri.fields_for :ingredient do |ing|%>
        <%=ing.label :name, "enter ing name"%>
        <%=ing.text_field :name%>
    <%end%>
 <%end%>

recipes_controller.rb

def new
    @recipe = Recipe.new
    5.times do 
        @recipe.recipe_ingredients.build.ingredient
    end
    5.times do 
        @recipe.ingredients.build
    end
end

Associations

A recipe has many ingredients through recipe_ingredients.

A ingredient has many recipes through recipe_ingredients.


I'm getting back only 1 input field for both cases, How can I do this?

1
use f.fields_for @recipe.recipe_ingredients - MrYoshiji
Do you know this? It's always helpful. - iGian
I tried the @recipe.recipe_ingredients modification but still no change, and I was looking at that page iGian but I could not make it work for me, or at least I could not find the controller file. - Ron

1 Answers

0
votes

Turns out that both methods work. All I was missing was adding "accepts_nested_attributes_for" in my Recipe model class.