使用一个 http 请求创建多个对象
Creating multiple objects with one http request
我有一个 rails 应用 json api。到目前为止,我可以通过 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"
}
]
}
但是,我不知道如何处理这个问题。第一个问题是我的强参数函数不接受数组。
有没有办法使用强参数并让我循环遍历数组?
我会将其视为一种新的控制器方法
类似于:
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
您还需要添加路线。然后你可以 post 你的 json 到那条路线,最外层的键应该是 customers
.
我不会 运行 这段代码不作任何更改,但您已经了解了大致的想法。您可以根据自己的喜好重构它。
我有一个 rails 应用 json api。到目前为止,我可以通过 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"
}
]
}
但是,我不知道如何处理这个问题。第一个问题是我的强参数函数不接受数组。 有没有办法使用强参数并让我循环遍历数组?
我会将其视为一种新的控制器方法
类似于:
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
您还需要添加路线。然后你可以 post 你的 json 到那条路线,最外层的键应该是 customers
.
我不会 运行 这段代码不作任何更改,但您已经了解了大致的想法。您可以根据自己的喜好重构它。