【发布时间】:2016-07-31 00:11:28
【问题描述】:
我在发送补丁请求时无法更新我的嵌套属性。当我更新我的食谱时,我想更新我的 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"
}]
}
}'
```
【问题讨论】:
-
请发布处理此更新的视图的
form_for部分。 -
我没有 form_for 部分。我还没有创建我的前端。我只是想发出 curl 请求来测试它是否有效;
-
那么您的
recipe.rb怎么样,以便仔细检查关系?我不能 100% 确定,因为我从来没有测试过没有表单的嵌套属性,但是使用form_for可能会有所作为。
标签: ruby-on-rails ruby curl nested-attributes