У меня возникают трудности с отправкой полезной нагрузки JSON в конечную точку, которая содержит вложенный ресурс, который я хотел бы создать с сохраненными и сохраненными связями ... независимо от того, что я делаю, в консоли отображается Unpermitted parameter: :ingredients
.
Модели / meal.rb
class Meal < ApplicationRecord
has_many :ingredients
accepts_nested_attributes_for :ingredients
end
Модели / ingredient.rb
class Ingredient < ApplicationRecord
belongs_to :meal
end
контроллер / 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
дб / мигрирует / 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" }
]
}
}
Я попробовал другой подход из статьи SO , столкнувшись с аналогичной проблемой, которая, казалось, распознавала параметр ингредиенты, но в итоге выкинула 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))
Любая помощь в указании моего недостатка очень ценится. И да, я хочу, чтобы ресурс вложенных ингредиентов был частью полезной нагрузки, идущей к этой конечной точке.