Seong Lee
Seong Lee

Reputation: 10520

Ruby on Rails 4 - form not updating additional field

I have recipe and ingredient model which have association set as

Recipe has_many :ingredients
accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true

Ingredient belongs_to :recipe

and strong parameter defined in recipes_controller

def recipe_params
  params.require(:recipe).permit(:title, :image, :serving, :prep, :cook, :steps, ingredients_attributes: [:id, :name, :_destroy])
end

and the submitted form sends the following parameters

Request

Parameters:

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"zT+9YEIh6ZNxO3wrV8ajj8NyVaTfPDel171hasWk2DA=",
 "recipe"=>{"title"=>"Recipe with image",
 "serving"=>"3",
 "prep"=>"10 min ",
 "cook"=>"19 min"},
 "ingredient"=>{"name"=>["Chicken", "Beef"]},
 "commit"=>"Update Recipe",
 "id"=>"4"}

The problem is that the additional ingredient Beef does not get persisted in the database. I wonder if I also have to pass in ingredient_id hash as defined in recipe_params or I need some kind of reference in the parameter for the association with recipe.

This additional field was generated with script and I don't think this value gets lost after form is submitted as it shows in the request parameters.

I would appreciate your input.

Upvotes: 0

Views: 55

Answers (1)

Sergey Gorlanov
Sergey Gorlanov

Reputation: 56

You use fields_for when create form in view? you post contain ingredient, but should be contained ingredients_attributes

Follow http://railscasts.com/episodes/196-nested-model-form-part-1

Upvotes: 2

Related Questions