我在發送修補程序請求時遇到更新嵌套屬性的問題。當我更新我的食譜時,我想更新我的recipe_ingredients。每次當我更新我的食譜時,食譜都會更新,但是recipe_ingredients只是追加該食譜。請幫幫忙〜感謝〜更新rails中的嵌套屬性
規則控制器
```
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"
}]
}
}'
```
請張貼處理這個更新視圖的'form_for'部分。 – MarsAtomic
我沒有form_for部分。我還沒有創建我的前端。我只是試圖讓curl請求來測試它是否有效; – tina
那麼你的'recipe.rb'那麼,爲了仔細檢查關係?我不是100%確定的,因爲我從來沒有測試沒有表單的嵌套屬性,但使用'form_for'可能會有所作爲。 – MarsAtomic