问题
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