Почему я не могу сохранить свои вложенные атрибуты, когда использую accepts_nested_attributes_for - PullRequest
0 голосов
/ 05 июня 2019

Используя почтальон, я пытаюсь ПОСТАВИТЬ новый рецепт, который имеет вложенные атрибуты тегов и ингредиентов.Отношения показаны в моделях ниже.

#Recipe Model

class Recipe < ApplicationRecord
  has_many :recipe_ingredients
  has_many :recipe_tags
  has_many :ingredients, :through => :recipe_ingredients
  has_many :tags, :through => :recipe_tags

  accepts_nested_attributes_for :ingredients, :tags

end

#Tag Model 

class Tag < ApplicationRecord
  has_many :recipe_tags
  has_many :recipes, :through => :recipe_tags

  def self.add_slugs
   update(slug: to_slug(tag_name))
  end

  def to_param
   slug
 end
end


#Ingredient Model

class Ingredient < ApplicationRecord
  has_many :recipe_ingredients
  has_many :recipes, :through => :recipe_ingredients
end


#Join Table for recipe and ingredients
 class RecipeIngredient < ApplicationRecord
  belongs_to :recipe, optional: true
  belongs_to :ingredient, optional: true
 end

#Join Table For recipe and tags 

class RecipeTag < ApplicationRecord
  belongs_to :recipe, optional: true
  belongs_to :tag, optional: true
end


Это мой контроллер рецептов, обрабатывающий запрос.

class Api::RecipesController < ApplicationController
  #before_action :authenticate_user

  def index
    @recipes = Recipe.all
    render json: @recipes, status: 200
  end

  def create
    @recipe = Recipe.new(recipe_params)
    #ingredient = @recipe.ingredients.build
    render json: @recipe, status: 200
  end

  def show
    @recipe = Recipe.find(params[:id])
    render json: @recipe, status: 200
  end

  private

  def recipe_params
    params.require(:recipe).permit(:name, :description, ingredients_attributes: [:id, :description], tags_attributes: [:id, :tag_name])
  end
end

Параметры, которые я отправляю от почтальона:

{
    "recipe":
    {
        "name": "Creamy Dill Chicken", 
        "description": "Dill has fresh and grassy flavor. Give it a small taste first if you are unfamiliar with the herb, and feel free to leave out some or all of it if too strong.", 
        "ingredients":[
            {
                "description": "Dill"
            }, 
            {
                "description": "Yukon Gold Potatoes"
            },
            {
                "description": "Asparagues"
            },
            {
                "description": "Chicken Breasts"
            },
            {
                "description": "Sour Cream"
            },
            {
                "description": "Chicken Stock concentrate"
            },
            {
                "description": "Dijon mustard"
            }
            ], 
        "tags": [
            {
                "tag_name": "Home Cooking"
            },
            {
                "tag_name": "American"
            }
            ]
    }
}

Я получаю только что созданный рецепт, но ингредиенты и массивы тегов пусты.В моей консоли я получаю

Unpermitted parameters: :ingredients, :tags

Мне интересно, почему эти параметры не сохраняются, когда я использую accepts_nested_attributes_for.Спасибо.

ОБНОВЛЕНИЕ

Проблема связана с телом в PostMan и изменением ингредиентов и тегов на ингридиенты ингредиентов и теги ингредиентов.Ниже приведен обновленный метод создания рельсов для моего RecipeController, чтобы фактически создать рецепт.Спасибо!

  def create
    @recipe = Recipe.new(recipe_params)
    @ingredients = recipe_params["ingredients_attributes"]
    @tags = recipe_params["tags_attributes"]
    @ingredients.each do |ingredient|
      @recipe.ingredients.build(ingredient)
    end

    @tags.each do |tag|
      @recipe.tags.build(tag)
    end

    if @recipe.save
      render json: @recipe, status: 200
    else
      render json: @recipe.errors, status: :unprocessable_entry
    end
  end

1 Ответ

2 голосов
/ 06 июня 2019

Это потому, что вы отправляете атрибуты, которые не разрешены с Postman.Попробуйте изменить атрибуты JSON, в частности замените ingredients на ingredients_attributes и tags на tags_attributes.

Ваше окончательное тело JSON должно выглядеть следующим образом:

{
  "recipe":
  {
    "name": "Creamy Dill Chicken", 
    "description": "Dill has fresh and grassy flavor. Give it a small taste first if you are unfamiliar with the herb, and feel free to leave out some or all of it if too strong.", 
    "ingredients_attributes": [
      ...
    ], 
    "tags_attributes": [
      ...
    ]
  }
}
...