Multiple Active Storage Services with Override for Test

Curated ago by @jeremysmithco


Active Storage services default to private access, unless you specifically make them public.

By default, Active Storage assumes private access to services. This means generating signed, single-use URLs for blobs. If you’d rather make blobs publicly accessible, specify public: true in your app’s config/storage.yml

But sometimes apps need both private and public services. For example, User avatars and Account logos could be accessed directly, but Account reports need an authorization check with a redirect to a signed, single-use URL.

You can pass the service option to has_one_attached or has_many_attached, but what if you want to use local storage for running tests? Here’s a way to do that.

class Account < ApplicationRecord
  has_one_attached :logo, service: storage_service(:amazon_public)
  has_one_attached :report, service: storage_service(:amazon_private)

The Account logo will use the public S3 bucket and the Account report will use the private S3 bucket.