JSON 负载中嵌套资源的不允许参数

Unpermitted Parameter for Nested Resource in JSON Payload

我很难将 JSON 有效载荷发送到包含嵌套资源的端点,我希望使用关联创建并保留嵌套资源...无论我做什么,我都会出现在控制台 Unpermitted parameter: :ingredients.

models/meal.rb

class Meal < ApplicationRecord
  has_many :ingredients
  accepts_nested_attributes_for :ingredients
end

models/ingredient.rb

class Ingredient < ApplicationRecord
  belongs_to :meal
end

controller/meals_controller.rb

class MealsController < ApplicationController
  def create
    @meal = Meal.new(meal_params)
    puts meal_params.inspect
    # just want to see the parameters in the log
    # ...
  end

  private
    def meal_params
      params.require(:meal).permit(
        :name,
        ingredients_attributes: [:id, :text]
      )
    end
  end

db/migrate/xxx_create_inredients.rb

class CreateIngredients < ActiveRecord::Migration[5.1]
  def change
    create_table :ingredients do |t|
      t.belongs_to :meal, index: true
      t.string :text
      t.timestamps
    end
  end
end

请求JSON有效载荷

{
  "meal": {
    "name": "My Favorite Meal",
    "ingredients": [
      { "text": "First ingredient" },
      { "text": "Second ingredient" }
    ]
  }
}

我尝试了另一种方法 遇到了类似的问题,似乎可以识别 ingredients 参数,但最终抛出 500: params.require(:meal).permit(:name, { ingredients: [:id, :text] })

这样做时,我收到以下信息: ActiveRecord::AssociationTypeMismatch (Ingredient(#70235637684840) expected, got {"text"=>"First Ingredient"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#70235636442880))


非常感谢任何指出我的缺陷的帮助。是的,我希望嵌套成分资源成为到达此端点的有效负载的一部分。

你在这里遇到的唯一问题是你的膳食参数 ingredients_attributes

def meal_params
  params.require(:meal).permit(
    :name,
    ingredients_attributes: [:id, :text]
  )
end

因此在您的有效负载中您也需要使用该密钥

{
  "meal": {
    "name": "My Favorite Meal",
    "ingredients_attributes": [
      { "text": "First ingredient" },
      { "text": "Second ingredient" }
    ]
  }
}

他们需要匹配。