TJ Sherrill
TJ Sherrill

Reputation: 2645

Using rails 4, how to deeply nest resources in a parent form

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

My Models:

Recipe

Recipe_Ingredient

Ingredient

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.

Upvotes: 0

Views: 52

Answers (1)

Drenmi
Drenmi

Reputation: 8777

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

Upvotes: 0

Related Questions