2016-07-31 152 views
0

我在發送修補程序請求時遇到更新嵌套屬性的問題。當我更新我的食譜時,我想更新我的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" 
             }] 
     } 
    }' 

```

+0

請張貼處理這個更新視圖的'form_for'部分。 – MarsAtomic

+0

我沒有form_for部分。我還沒有創建我的前端。我只是試圖讓curl請求來測試它是否有效; – tina

+0

那麼你的'recipe.rb'那麼,爲了仔細檢查關係?我不是100%確定的,因爲我從來沒有測試沒有表單的嵌套屬性,但使用'form_for'可能會有所作爲。 – MarsAtomic

回答

0

您需要發送您的recipe_ingredientsid在捲曲請求軌道更新正確的現有recipe_ingredient記錄。否則,軌道將創造一個新的紀錄。例如,這將更新recipe_ingredientid 1,創造新的「豆漿」原料:

"recipe_ingredients_attributes": [{ "id": 1 "amount": 1, "ingredient": "egg yolk", "measure": "cup" }, { "amount": 3, "ingredient": "soy milk", "measure": "cup" }]

+0

是的。這可以解決問題。但我不確定每次創建新配方時如何跟蹤recipe_ingredients的ID。由於recipe_ingredients是配方的嵌套屬性。我想在更新我的食譜時更新它們。當創建父母或更新父母時,是否有任何軌道「技巧」用於跟蹤孩子ID?感謝您的建議〜 – tina

+0

當您想更新配方時,您需要首先獲取其數據以顯示,對不對?我的意思是你必須在'update'之前'show'。因此,在「show」動作中,您返回該配方中每種成分的ID,以便您知道要更新哪種成分以發送正確的ID。創建食譜時,你正在創造新的食材,所以不需要知道他們的ID。 – Canh