Update nested attributes in rails

最后都变了- 提交于 2019-12-25 09:06:03

问题


I am having trouble with updating my nested attributes when I sending patch request. I want to update my recipe_ingredients when I update my recipe. Every time when I update my recipe, recipe gets updated, but recipe_ingredients are just appending for that recipe. Please help~ Many thanks~

Recipe Controller

```

  def update
    @recipe = Recipe.find(params[:id])
    if @recipe.update(recipe_params)
       @recipe_ingredients = @recipe.recipe_ingredients.all
       head :no_content
    else
       render json: @recipe.errors, status: :unprocessable_entity
    end
  end

  def recipe_params
  params.require(:recipes)
        .permit(:name, :category, instructions: [],  recipe_ingredients_attributes: [:id, :recipe_id, :ingredient, :measure, :amount])
end

```

Recipe Model:

```

class Recipe < ActiveRecord::Base
   has_many :recipe_ingredients, dependent: :destroy
   accepts_nested_attributes_for :recipe_ingredients, allow_destroy: true, update_only: true
end

```

Curl Request: ```

   curl --include --request PATCH http://localhost:3000/recipes/1 \
   --header "Authorization: Token token=..." \
   --header "Content-Type: application/json" \
   --data '{
      "recipes": {
      "name": "second example recipe",
      "category": "grill",
      "instructions": ["do it", "ignore it"],
      "recipe_ingredients_attributes": [{
                                         "amount": 1,
                                         "ingredient": "egg yolk",
                                         "measure": "cup"
                                        },
                                        {
                                         "amount": 3,
                                         "ingredient": "soy milk",
                                         "measure": "cup"
                                        }]
      }
    }'

```


回答1:


You need to send id of your recipe_ingredients in the curl request for rails to update the correct existing recipe_ingredient records. Otherwise, rails will create a new record. For example, this will update recipe_ingredient with id 1 and create new "soy milk" ingredient:

"recipe_ingredients_attributes": [{ "id": 1 "amount": 1, "ingredient": "egg yolk", "measure": "cup" }, { "amount": 3, "ingredient": "soy milk", "measure": "cup" }]



来源:https://stackoverflow.com/questions/38679639/update-nested-attributes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!