【问题标题】:Update nested attributes in rails更新 Rails 中的嵌套属性
【发布时间】: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


【解决方案1】:

您需要在 curl 请求中发送您的 recipe_ingredients 中的 id 以更新正确的现有 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"
                                   }]

【讨论】:

  • 是的。这可以解决问题。但我不确定每次创建新食谱时如何跟踪 recipe_ingredients 的 id。因为 recipe_ingredients 是配方的嵌套属性。当我更新我的食谱时,我想更新它们。创建父级或更新父级时是否有任何轨道“技巧”来跟踪子级 ID?谢谢你的建议~
  • 当你想更新一个菜谱时,你需要先获取它的数据才能显示,对吧?我的意思是你必须在update 之前show。因此,在show 操作中,您返回该配方的每种成分的 ID,以便您知道要更新哪个成分以发送正确的 ID。在创建食谱时,您正在创建新成分,因此无需知道它们的 ID。
最近更新 更多