【问题标题】:Creating multiple objects with one http request使用一个 http 请求创建多个对象
【发布时间】:2015-03-16 09:01:45
【问题描述】:

我有一个带有 json api 的 rails 应用程序。到目前为止,我可以通过 POST 请求创建单个对象。

这很简单:

def create
    customer = Customer.new(customer_params)
    if customer.save
        render json: customer, status: 201
    else
        render json: customer.errors, status: 422
    end
end

和:

private
        def customer_params 
            params.require(:customer).permit(:name, :city)
        end

现在我想通过在我的 http 请求中传递一个数组来创建多个客户。像这样:

{
"customer": [
    {
        "name": "foo",
        "city": "New York"
    },
    {
        "name": "bar",
        "city": "Chicago"
     }
  ]
}

但是,我不知道如何处理这个问题。第一个问题是我的强参数函数不接受数组。 有没有办法使用强参数让我循环遍历数组?

【问题讨论】:

    标签: ruby-on-rails activerecord strong-parameters


    【解决方案1】:

    我认为它是一种新的控制器方法

    类似:

    def multi_create
      render json: customer.errors, status: 422 and return unless params[:customers]
      all_created = true
      customers = []
      params[:customers].each do |customer_params|
        customer = Customer.create(name: customer_params[:name], city: customer_params[:city])
        customers << customer
        all_created &&= customer.valid?
      end
    
      if all_created
        render json: customers, status: 201
      else
        render json: customers.map(&:errors), status: 422
      end 
    end
    

    您还需要添加路线。然后你可以将你的 json 发布到那个路由,最外层的键应该是customers

    我不会在不做任何更改的情况下运行此代码,但您大致了解。您可以根据自己的喜好对其进行重构。

    【讨论】:

    • 这或多或少是正确的(取决于用例),但是在添加任何客户失败的情况下需要额外的处理程序(例如transaction)。现在,如果有任何故障,所有剩余的都留在数据库中。
    • 我同意。最重要的是,它需要决定如何处理一个或多个创建失败的请求。如果您想回滚所有内容或您想要实现的目标。这或多或少是我最后一行关于变化的意思......
    猜你喜欢
    • 2011-02-18
    • 2015-04-09
    • 2017-09-12
    • 2017-05-02
    • 2015-10-14
    • 1970-01-01
    • 2017-08-04
    • 2021-08-01
    • 2021-05-24
    相关资源
    最近更新 更多