发送补丁请求时,我无法更新嵌套属性。我想在更新食谱时更新我的recipe_ingredients。每当我更新我的食谱时,食谱都会更新,但recipe_ingredients只是为该食谱添加。请帮忙〜非常感谢〜
配方控制器
```
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
```
食谱模型:
```
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients, dependent: :destroy
accepts_nested_attributes_for :recipe_ingredients, allow_destroy: true, update_only: true
end
```
卷曲请求: ```
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"
}]
}
}'
```
答案 0 :(得分:0)
您需要在curl curl请求中发送id
recipe_ingredients
来更新正确的现有recipe_ingredient
记录。否则,rails将创建一个新记录。例如,这将使用recipe_ingredient
更新id 1
并创建新的“豆浆”成分:
"recipe_ingredients_attributes": [{
"id": 1
"amount": 1,
"ingredient": "egg yolk",
"measure": "cup"
},
{
"amount": 3,
"ingredient": "soy milk",
"measure": "cup"
}]