How to upload and save multiple images to Rails API from JS frontend

Viewed 16

I am sending data from ReactJS as multipart/form-data to Rails API like this:

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

On the Rails side I use ActiveStorage and attach images in update action like this:

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

My env:

Ruby 3.0.1
Rails 6.1.4.1

Is there a better (cleaner) way to attach multiple images on the Rails side?

1 Answers
Related