author avatar

syedsibtain

Tue Aug 27 2024

Handling Image Uploads with Active Storage in Rails

Active Storage simplifies file uploads in Rails by attaching files to models.

Setup: Install Active Storage and run rails active_storage:install and rails db:migrate to create necessary tables.

Model Configuration: Use has_many_attached :images to allow multiple image uploads in our model. Example:

class SomeModel < ApplicationRecord
  has_many_attached :images
end

Form: Ensure the form includes multipart: true and allows multiple file uploads with form.file_field :images, multiple: true.

Controller: Permit images in the strong parameters with images: []. Example:

def some_params
  params.require(:some_model).permit(:note, images: [])
end

Migration: Remove old image columns if switching from direct storage to Active Storage. <#CU6U0R822|> #activestorage #fileupload