0
votes

Writing a recipe app. Having a hell of a time getting this down.

My Models:

Recipe

  • has_many :recipe_ingredients
  • has_many :ingredients, through: :recipe_ingredients

Recipe_Ingredient

  • belongs_to :recipe
  • belongs_to :ingredient

Ingredient

  • has_many :recipe_ingredients, :dependent => :destroy
  • has_many :recipes, through: :recipe_ingredients

My routes are simple

resources :recipes // AND A FEW RANDOM OTHERS

In my Recipes Controller:

def new
    @recipe = Recipe.new
    recipe_ingredients = @recipe.recipe_ingredient.build
    recipe_ingredients.ingredient.build
end

My Recipe Form:

<%= simple_form_for @recipe do |r| %>

<%= r.input :title, label: 'Recipe Name:' %>
<%= r.input :description, label: 'Recipe Description' %>

<%= r.simple_fields_for :recipe_ingredients do |ri| %>
  <%= ri.input :quantity, label: "Quantity" %>
  <%= ri.simple_fields_for :ingredients do |i| %>
      <%= i.input :name, label: "name" %>
  <% end %> 
<% end %> 
<%= r.button :submit %>
<% end %>

Not sure what I am doing wrong. The error is:

undefined method `recipe_ingredient' for #<Recipe:0x000001034d3650>

any ideas? Spent 2 nights on this.

1

1 Answers

0
votes

The particular error seems to come from referencing @recipe.recipe_ingredient (singular), which should be pluralized, since it is a has_many relation. Try this in your RecipeController#new:

recipe_ingredients = @recipe.recipe_ingredients.build

Then, for the recipe_ingredients.ingredient, try using build_association instead:

recipe_ingredients.build_ingredient