rails 多个创建(JSON 通过 POSTMAN)

rails multiple create (JSON through POSTMAN)

我想创建一个API,我需要创建多个post,像这样(但列表可以达到未定义的项目数):

{"item":{"name":"Objeto 1","description":"Descripcion 1","price":100}},
{"item":{"name":"Objeto 2","description":"Descripcion 2","price":200}},
{"item":{"name":"Objeto 3","description":"Descripcion 3","price":300}},
{"item":{"name":"Objeto 4","description":"Descripcion 3","price":400}}

我有这个控制器:

class ItemController < ApplicationController
  before_action :set_item, only: [:show, :update, :destroy]

  # GET /item
  # GET /item.json
  def index
    @item = Item.all

    render json: @items
  end

  # GET /items/1
  # GET /items/1.json
  def show
    render json: @item
  end

  # POST /items
  # POST /items.json
  def create
    @item = Item.new(item_params)

    if @item.save
      render json: @item, status: :created, location: @item
    else
      render json: @item.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /items/1
  # PATCH/PUT /items/1.json
  def update
    @item = Item.find(params[:id])

    if @item.update(item_params)
      head :no_content
    else
      render json: @item.errors, status: :unprocessable_entity
    end
  end

  # DELETE /items/1
  # DELETE /items/1.json
  def destroy
    @item.destroy

    head :no_content
  end

  private

    def set_item
      @item = Item.find(params[:id])
    end

    def item_params
      params.require(:item).permit(:name, :description, :price)
    end
end

我的问题是,我该如何使用这份清单?我需要创建一个新方法吗? 我正在通过 POSTMAN

发送 JSON 数组

这是模型

class Item < ActiveRecord::Base

end

选项 1

不更改您的 ItemsController...

在 Postman 中,您需要一次执行一个请求,如下所示:


选项 2

如果您想发送多个项目,您需要修改创建操作以接受多个项目或添加一个新项目来处理此问题。 例如,您可以创建 create_many 操作:

/your-app/config/routes.rb

Rails.application.routes.draw do
  resources :items do
    collection do
      post 'create_many'
    end
  end
end

/your-app/app/controllers/items_controller.rb

class ItemsController < ApplicationController
  # other actions...

  def create_many
    # I've done a very basic implementation.
    # I think you can use a service to extract from the controller the ability to create multiple items and handle errors.
    # See "2. Extract Service Objects" http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/)
    @items = []
    items_params[:items].each do |item_data|
      @items << Item.create(item_data)
    end
  end

  private

  def items_params
    params.permit(items: [:name, :description, :price])
  end
end

/your-app/app/views/items/create_many.html.erb

<%= @items.inspect %>

邮递员可以做的事:


选项 3

我问过你关于模型的问题,因为如果你有一个 "user has_many :items" 关系,你可以使用 nested attributes

以 Rails 的方式创建嵌套项目