Rails 3 using view fields does not work

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 #belongs_to :ingredient end 

In the new controller, I populate the ingredients with three blank entries:

 def new @recipe = Recipe.new 3.times {@recipe.recipe_ingredients.build} # @ingredients = RecipeIngredient.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @recipe } end end 

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?

+4
source share
2 answers

Switch it to

 <% form_for :recipe do |f| %> <% f.fields_for :ingredients do |ingredient_form| %> <p> Ingredient: <%= ingredient_form.text_field :description %> </p> <% end %> <% end %> 
+5
source

You should use <% = instead of <% when using form_for and fields_for

The correct code should look like this:

 <%= form_for :recipe do |f| %> <%= f.fields_for :ingredients do |ingredient_form| %> <p> Ingredient: <%= ingredient_form.text_field :description %> </p> <% end %> <% end %> 
+27
source

All Articles