如何从JS前端上传和保存多个图像到Railsneneneba API



我将数据从ReactJS作为多部分/form-data发送到Rails API,如下所示:

const submitProduct = formData => {
const config = {
method: "PATCH",
headers: {
"Accept": "application/json"
},
body: formData
}
return fetch(PRODUCT_URL, config)
.then(res => res.json());
}

在Rails方面,我使用ActiveStorage并在update操作中附加图像,如下所示:

if params[:images].present?
params[:images].each do |image|
@product.images.attach(image)
end
end

有没有更好(更干净(的方法在Rails端附加多个图像?

我的环境:

Ruby 3.0.1
Rails 6.1.4.1

参考:

  • https://guides.rubyonrails.org/v6.1/active_storage_overview.html#has-许多附加

如果您的params[:images]是上传文件对象的数组,那么您应该能够像一样一次附加所有对象

@product.images.attach(params[:images])

请参阅此处了解更多信息:https://edgeapi.rubyonrails.org/classes/ActiveStorage/Attached/Many.html#method-i-attach

最新更新