I am trying to implement a main part in the form of rails with fields_for.
I have one model called "Recipe":
class Recipe < ActiveRecord::Base validates :name, :presence => true validates :directions, :presence => true has_many :recipe_ingredients end
and one model called RecipeIngredient:
class RecipeIngredient < ActiveRecord::Base belongs_to :recipe
In the new controller, I populate the ingredients with three blank entries:
def new @recipe = Recipe.new 3.times {@recipe.recipe_ingredients.build}
What I would like to do in the view is to display the recipe fields (which work fine) and the three fields for the recipe ingredients. At the top of the view, I have the following:
<%= form_for :rec do |f| %>
Then I list the correct recipe fields, for example:
<div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div>
Then I try to display the rows of ingredients, but the code never ends up in the fields_for section:
first try:
<% for ingredient in @recipe.recipe_ingredients %> This prints out three times <% fields_for "...", ingredient do |ingredient_form| %> But this never prints out <p> Ingredient: <%= ingredient_form.text_field :description %> </p> <% end %> <% end%>
I have three empty lines in recipe_ingredients, and the for loop seems to repeat three times, but the code inside the fields does not start.
Second attempt:
<% for recipe_ingredient in @recipe.recipe_ingredients %> b <% fields_for "...", recipe_ingredient do |recipe_ingredient| %> Rec: <%= recipe_ingredient.text_field :description %> <% end %> <% end %>
Third attempt (based on answer here):
<% form_for :recipe do |f| %> <% f.fields_for ingredients do |ingredient_form| %> <p> Ingredient: <%= ingredient_form.text_field :description %> </p> <% end %> <% end %>
Is there something obvious I'm doing wrong?