Active Storage

Active Storage makes it simple to upload and reference files in cloud services, like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects. It comes with a local disk-based service for development and testing which supports mirroring files to subordinate services for backups and migrations.

Files can be uploaded from the server to the cloud or directly from the client to the cloud.

Image files can furthermore be transformed using on-demand variants for quality, aspect ratio, size, or any other MiniMagick supported transformation.

Before starting this tutorial, I assume that you have Basic Rails application created.

Read more: 10 best Ruby Gems for Rails Development

Installation and migration

  1. Add gem “activestorage”, git: “https://github.com/rails/activestorage.git” to your Gemfile.
  2. Add require “active_storage” to config/application.rb, after require “rails/all” line.
  3. Optional: Add gem “mini_magick” to your Gemfile if you want to use variants.

Setup

Active Storage uses two tables in your application’s database named active_storage_blobs and active_storage_attachments. After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables. Use rails db: migrate to run the migration.

Default Active storage Image Saving Path

Declare Active Storage services in config/storage.yml. For each service, your application uses, provide a name and the requisite configuration. The example below declares three services named local, test, and Amazon:

OR

Dynamic Active storage Image Saving Path

Tell Active Storage which service to use by setting Rails.application.config.active_storage.service. Because each environment will likely use a different service, it is recommended to do this on a per-environment basis. To use the disk service from the previous example in the development environment, you would add the following to config/environments/development.rb:

Store file locally:

Example:

Routes

Model

new.html.erb

show.html.erb

profile_info.js

Controller

Click here for more details


At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.

We also specialize in RPA, AI, Python, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!