Skip to content

Instantly share code, notes, and snippets.

@vampaynani
Created August 25, 2021 08:55
Show Gist options
  • Save vampaynani/0cafad28495ea89211dcb4a48a7a5417 to your computer and use it in GitHub Desktop.
Save vampaynani/0cafad28495ea89211dcb4a48a7a5417 to your computer and use it in GitHub Desktop.
Setup Active Storage

Implement Active Storage

Uncomment gem "image_processing", ">= 1.2" on Gemfile.

Run bundle install.

Run rails active_storage:install to generate a migration, it will create 3 tables: active_storage_blobs, active_storage_variant_records and active_storage_attachments.

Run rails db:migrate.

Make sure Active Storage local service is uncommented in config/storage.yml.

Tell Active Storage which service to use by setting config.active_storage.service. To use the disk service from the previous example in the development environment,make sure the following line is active on config/environments/development.rb, if not, add it:

# config/environments/development.rb
config.active_storage.service = :local

Attach a file to a record. On the model add has_one_attached and the field name as in the example:

class User < ApplicationRecord
  has_one_attached :avatar
end

Add a file_field to the create and update forms

<%= form.file_field :avatar %>

Do not forget to update the permitted params at the controller

def user_params
  params.require(:user).permit(:email_address, :password, :avatar)
end

Finally, show the image at the detailed view if there is an attached image

<%= image_tag user.avatar, size: "320x240" if user.avatar.attached? %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment