Module: ActiveStorage
Overview
:markup: markdown Active Storage makes it simple to upload and reference files in cloud services like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage, and attach those files to Active Records. Supports having one main service and mirrors in other services for redundancy. It also provides a disk service for testing or local deployments, but the focus is on cloud storage.
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 or Vips supported transformation.
You can read more about Active Storage in the Active Storage Overview guide.
==== Compared to other storage solutions
A key difference to how Active Storage works compared to other attachment solutions in \Rails is through the use of built-in Blob and Attachment models (backed by Active Record). This means existing application models do not need to be modified with additional columns to associate with files. Active Storage uses polymorphic associations via the Attachment
join model, which then connects to the actual Blob
.
Blob
models store attachment metadata (filename, content-type, etc.), and their identifier key in the storage service. Blob models do not store the actual binary data. They are intended to be immutable in spirit. One file, one blob. You can associate the same blob with multiple application models as well. And if you want to do transformations of a given Blob
, the idea is that you'll simply create a new one, rather than attempt to mutate the existing one (though of course you can delete the previous version later if you don't need it).
==== Installation
Run bin/rails active_storage:install
to copy over active_storage migrations.
NOTE: If the task cannot be found, verify that require "active_storage/engine"
is present in config/application.rb
.
==== Examples
One attachment:
class User < ApplicationRecord
# Associates an attachment and a blob. When the user is destroyed they are
# purged by default (models destroyed, and resource files deleted).
has_one_attached :avatar
end
=== Attach an avatar to the user.
user.avatar.attach(io: {File.open}("/path/to/face.jpg"), filename: "face.jpg", content_type: "image/jpeg")
=== Does the user have an avatar?
user.avatar.attached? # => true
=== Synchronously destroy the avatar and actual resource files.
user.avatar.purge
=== Destroy the associated models and actual resource files async, via Active Job.
user.avatar.purge_later
=== Does the user have an avatar?
user.avatar.attached? # => false
=== Generate a permanent URL for the blob that points to the application.
=== Upon access, a redirect to the actual service endpoint is returned.
=== This indirection decouples the public URL from the actual one, and
=== allows for example mirroring in different services for
=== high-availability. The redirection has an HTTP expiration of 5 min.
url_for(user.avatar)
class AvatarsController < ApplicationController
def update
# params[:avatar] contains an ActionDispatch::Http::UploadedFile object
Current.user.avatar.attach(params.require(:avatar))
redirect_to Current.user
end
end
Many attachments:
class Message < ApplicationRecord
has_many_attached :images
end
<%= form_with model: @message, local: true do |form| %>
<%= form.text_field :title, placeholder: "Title" %><br>
<%= form.text_area :content %><br><br>
<%= form.file_field :images, multiple: true %><br>
<%= form.submit %>
<% end %>
class MessagesController < ApplicationController
def index
# Use the built-in with_attached_images scope to avoid N+1
@messages = Message.all.with_attached_images
end
def create
= Message.create! params.require(: ).permit(:title, :content, images: [])
redirect_to
end
def show
@message = Message.find(params[:id])
end
end
Variation of image attachment:
<%# Hitting the variant URL will lazy transform the original blob and then redirect to its new service location %>
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>
==== File serving strategies
Active Storage supports two ways to serve files: redirecting and proxying.
===== Redirecting
Active Storage generates stable application URLs for files which, when accessed, redirect to signed, short-lived service URLs. This relieves application servers of the burden of serving file data. It is the default file serving strategy.
When the application is configured to proxy files by default, use the rails_storage_redirect_path
and _url
route helpers to redirect instead:
<%= image_tag rails_storage_redirect_path(@user.avatar) %>
===== Proxying
Optionally, files can be proxied instead. This means that your application servers will download file data from the storage service in response to requests. This can be useful for serving files from a CDN.
You can configure Active Storage to use proxying by default:
=== config/initializers/active_storage.rb
{Rails.application}.config.active_storage.resolve_model_to_route = :rails_storage_proxy
Or if you want to explicitly proxy specific attachments there are URL helpers you can use in the form of rails_storage_proxy_path
and rails_storage_proxy_url
.
<%= image_tag rails_storage_proxy_path(@user.avatar) %>
==== Direct uploads
Active Storage, with its included JavaScript library, supports uploading directly from the client to the cloud.
===== Direct upload installation
Include the Active Storage JavaScript in your application's JavaScript bundle or reference it directly.
Requiring directly without bundling through the asset pipeline in the application HTML with autostart:
<%= javascript_include_tag "activestorage" %>
Requiring via importmap-rails without bundling through the asset pipeline in the application HTML without autostart as ESM:
# config/importmap.rb pin "@rails/activestorage", to: "activestorage.esm.js"
<script type="module-shim"> import * as ActiveStorage from "@rails/activestorage" ActiveStorage.start() </script>
Using the asset pipeline:
//= require activestorage
Using the npm package:
import * as ActiveStorage from "@rails/activestorage" ActiveStorage.start()
Annotate file inputs with the direct upload URL.
<%= form.file_field :attachments, multiple: true, direct_upload: true %>
That's it! Uploads begin upon form submission.
===== Direct upload JavaScript events
Event name | Event target | Event data (event.detail ) |
Description |
---|---|---|---|
direct-uploads:start |
|
None | A form containing files for direct upload fields was submitted. |
direct-upload:initialize |
|
{id, file} |
Dispatched for every file after form submission. |
direct-upload:start |
|
{id, file} |
A direct upload is starting. |
direct-upload:before-blob-request |
|
{id, file, xhr} |
Before making a request to your application for direct upload metadata. |
direct-upload:before-storage-request |
|
{id, file, xhr} |
Before making a request to store a file. |
direct-upload:progress |
|
{id, file, progress} |
As requests to store files progress. |
direct-upload:error |
|
{id, file, error} |
An error occurred. An alert will display unless this event is canceled. |
direct-upload:end |
|
{id, file} |
A direct upload has ended. |
direct-uploads:end |
|
None | All direct uploads have ended. |
==== License
Active Storage is released under the MIT License.
==== Support
API documentation is at:
Bug reports for the Ruby on \Rails project can be filed here:
Feature requests should be discussed on the rails-core mailing list here:
Class Attribute Summary
- .analyzers (also: #analyzers) rw
- .binary_content_type (also: #binary_content_type) rw
- .content_types_allowed_inline (also: #content_types_allowed_inline) rw
- .content_types_to_serve_as_binary (also: #content_types_to_serve_as_binary) rw
- .draw_routes (also: #draw_routes) rw
- .logger (also: #logger) rw
- .paths (also: #paths) rw
- .previewers (also: #previewers) rw
- .queues (also: #queues) rw
- .replace_on_assign_to_many rw
- .replace_on_assign_to_many=(value) rw
- .resolve_model_to_route (also: #resolve_model_to_route) rw
- .routes_prefix (also: #routes_prefix) rw
- .service_urls_expire_in (also: #service_urls_expire_in) rw
- .silence_invalid_content_types_warning rw
- .silence_invalid_content_types_warning=(value) rw
- .supported_image_processing_methods (also: #supported_image_processing_methods) rw
- .track_variants (also: #track_variants) rw
- .unsupported_image_processing_arguments (also: #unsupported_image_processing_arguments) rw
- .urls_expire_in (also: #urls_expire_in) rw
- .variable_content_types (also: #variable_content_types) rw
- .variant_processor (also: #variant_processor) rw
- .verifier (also: #verifier) rw
- .video_preview_arguments (also: #video_preview_arguments) rw
- .web_image_content_types (also: #web_image_content_types) rw
Class Method Summary
-
.gem_version
Returns the currently loaded version of Active Storage as a
Gem::Version
. -
.version
Returns the currently loaded version of Active Storage as a
Gem::Version
.
::ActiveSupport::Autoload
- Extended
Instance Attribute Summary
- #analyzers rw
- #binary_content_type rw
- #content_types_allowed_inline rw
- #content_types_to_serve_as_binary rw
- #draw_routes rw
- #logger rw
- #paths rw
- #previewers rw
- #queues rw
- #resolve_model_to_route rw
- #routes_prefix rw
- #service_urls_expire_in rw
- #supported_image_processing_methods rw
- #track_variants rw
- #unsupported_image_processing_arguments rw
- #urls_expire_in rw
- #variable_content_types rw
- #variant_processor rw
- #verifier rw
- #video_preview_arguments rw
- #web_image_content_types rw
Class Attribute Details
.analyzers (rw) Also known as: #analyzers
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 55
mattr_accessor :analyzers, default: []
.binary_content_type (rw) Also known as: #binary_content_type
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 61
mattr_accessor :binary_content_type, default: "application/octet-stream"
.content_types_allowed_inline (rw) Also known as: #content_types_allowed_inline
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 63
mattr_accessor :content_types_allowed_inline, default: []
.content_types_to_serve_as_binary (rw) Also known as: #content_types_to_serve_as_binary
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 62
mattr_accessor :content_types_to_serve_as_binary, default: []
.draw_routes (rw) Also known as: #draw_routes
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 360
mattr_accessor :draw_routes, default: true
.logger (rw) Also known as: #logger
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 48
mattr_accessor :logger
.paths (rw) Also known as: #paths
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 57
mattr_accessor :paths, default: {}
.previewers (rw) Also known as: #previewers
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 54
mattr_accessor :previewers, default: []
.queues (rw) Also known as: #queues
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 52
mattr_accessor :queues, default: {}
.replace_on_assign_to_many (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 367
def self.replace_on_assign_to_many ActiveStorage.deprecator.warn("config.active_storage.replace_on_assign_to_many is deprecated and has no effect.") end
.replace_on_assign_to_many=(value) (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 371
def self.replace_on_assign_to_many=(value) ActiveStorage.deprecator.warn("config.active_storage.replace_on_assign_to_many is deprecated and has no effect.") end
.resolve_model_to_route (rw) Also known as: #resolve_model_to_route
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 361
mattr_accessor :resolve_model_to_route, default: :rails_storage_redirect
.routes_prefix (rw) Also known as: #routes_prefix
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 359
mattr_accessor :routes_prefix, default: "/rails/active_storage"
.service_urls_expire_in (rw) Also known as: #service_urls_expire_in
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 356
mattr_accessor :service_urls_expire_in, default: 5.minutes
.silence_invalid_content_types_warning (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 375
def self.silence_invalid_content_types_warning ActiveStorage.deprecator.warn("config.active_storage.silence_invalid_content_types_warning is deprecated and has no effect.") end
.silence_invalid_content_types_warning=(value) (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 379
def self.silence_invalid_content_types_warning=(value) ActiveStorage.deprecator.warn("config.active_storage.silence_invalid_content_types_warning is deprecated and has no effect.") end
.supported_image_processing_methods (rw) Also known as: #supported_image_processing_methods
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 65
mattr_accessor :supported_image_processing_methods, default: [ "adaptive_blur", "adaptive_resize", "adaptive_sharpen", "adjoin", "affine", "alpha", "annotate", "antialias", "append", "apply", "attenuate", "authenticate", "auto_gamma", "auto_level", "auto_orient", "auto_threshold", "backdrop", "background", "bench", "bias", "bilateral_blur", "black_point_compensation", "black_threshold", "blend", "blue_primary", "blue_shift", "blur", "border", "bordercolor", "borderwidth", "brightness_contrast", "cache", "canny", "caption", "channel", "channel_fx", "charcoal", "chop", "clahe", "clamp", "clip", "clip_path", "clone", "clut", "coalesce", "colorize", "colormap", "color_matrix", "colors", "colorspace", "colourspace", "color_threshold", "combine", "combine_options", "comment", "compare", "complex", "compose", "composite", "compress", "connected_components", "contrast", "contrast_stretch", "convert", "convolve", "copy", "crop", "cycle", "deconstruct", "define", "delay", "delete", "density", "depth", "descend", "deskew", "despeckle", "direction", "displace", "dispose", "dissimilarity_threshold", "dissolve", "distort", "dither", "draw", "duplicate", "edge", "emboss", "encoding", "endian", "enhance", "equalize", "evaluate", "evaluate_sequence", "extent", "extract", "family", "features", "fft", "fill", "filter", "flatten", "flip", "floodfill", "flop", "font", "foreground", "format", "frame", "function", "fuzz", "fx", "gamma", "gaussian_blur", "geometry", "gravity", "grayscale", "green_primary", "hald_clut", "highlight_color", "hough_lines", "iconGeometry", "iconic", "identify", "ift", "illuminant", "immutable", "implode", "insert", "intensity", "intent", "interlace", "interline_spacing", "interpolate", "interpolative_resize", "interword_spacing", "kerning", "kmeans", "kuwahara", "label", "lat", "layers", "level", "level_colors", "limit", "limits", "linear_stretch", "linewidth", "liquid_rescale", "list", "loader", "log", "loop", "lowlight_color", "magnify", "map", "mattecolor", "median", "mean_shift", "metric", "mode", "modulate", "moments", "monitor", "monochrome", "morph", "morphology", "mosaic", "motion_blur", "name", "negate", "noise", "normalize", "opaque", "ordered_dither", "orient", "page", "paint", "pause", "perceptible", "ping", "pointsize", "polaroid", "poly", "posterize", "precision", "preview", "process", "quality", "quantize", "quiet", "radial_blur", "raise", "random_threshold", "range_threshold", "red_primary", "regard_warnings", "region", "remote", "render", "repage", "resample", "resize", "resize_to_fill", "resize_to_fit", "resize_to_limit", "resize_and_pad", "respect_parentheses", "reverse", "roll", "rotate", "sample", "sampling_factor", "saver", "scale", "scene", "screen", "seed", "segment", "selective_blur", "separate", "sepia_tone", "shade", "shadow", "shared_memory", "sharpen", "shave", "shear", "sigmoidal_contrast", "silent", "similarity_threshold", "size", "sketch", "smush", "snaps", "solarize", "sort_pixels", "sparse_color", "splice", "spread", "statistic", "stegano", "stereo", "storage_type", "stretch", "strip", "stroke", "strokewidth", "style", "subimage_search", "swap", "swirl", "synchronize", "taint", "text_font", "threshold", "thumbnail", "tile_offset", "tint", "title", "transform", "transparent", "transparent_color", "transpose", "transverse", "treedepth", "trim", "type", "undercolor", "unique_colors", "units", "unsharp", "update", "valid_image", "view", "vignette", "virtual_pixel", "visual", "watermark", "wave", "wavelet_denoise", "weight", "white_balance", "white_point", "white_threshold", "window", "window_group" ]
.track_variants (rw) Also known as: #track_variants
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 363
mattr_accessor :track_variants, default: false
.unsupported_image_processing_arguments (rw) Also known as: #unsupported_image_processing_arguments
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 354
mattr_accessor :unsupported_image_processing_arguments
.urls_expire_in (rw) Also known as: #urls_expire_in
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 357
mattr_accessor :urls_expire_in
.variable_content_types (rw) Also known as: #variable_content_types
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 59
mattr_accessor :variable_content_types, default: []
.variant_processor (rw) Also known as: #variant_processor
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 50
mattr_accessor :variant_processor, default: :mini_magick
.verifier (rw) Also known as: #verifier
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 49
mattr_accessor :verifier
.video_preview_arguments (rw) Also known as: #video_preview_arguments
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 365
mattr_accessor :video_preview_arguments, default: "-y -vframes 1 -f image2"
.web_image_content_types (rw) Also known as: #web_image_content_types
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 60
mattr_accessor :web_image_content_types, default: []
Class Method Details
.gem_version
Returns the currently loaded version of Active Storage as a Gem::Version
.
.version
Returns the currently loaded version of Active Storage as a Gem::Version
.
# File 'activestorage/lib/active_storage/version.rb', line 7
def self.version gem_version end
Instance Attribute Details
#analyzers (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 55
mattr_accessor :analyzers, default: []
#binary_content_type (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 61
mattr_accessor :binary_content_type, default: "application/octet-stream"
#content_types_allowed_inline (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 63
mattr_accessor :content_types_allowed_inline, default: []
#content_types_to_serve_as_binary (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 62
mattr_accessor :content_types_to_serve_as_binary, default: []
#draw_routes (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 360
mattr_accessor :draw_routes, default: true
#logger (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 48
mattr_accessor :logger
#paths (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 57
mattr_accessor :paths, default: {}
#previewers (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 54
mattr_accessor :previewers, default: []
#queues (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 52
mattr_accessor :queues, default: {}
#resolve_model_to_route (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 361
mattr_accessor :resolve_model_to_route, default: :rails_storage_redirect
#routes_prefix (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 359
mattr_accessor :routes_prefix, default: "/rails/active_storage"
#service_urls_expire_in (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 356
mattr_accessor :service_urls_expire_in, default: 5.minutes
#supported_image_processing_methods (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 65
mattr_accessor :supported_image_processing_methods, default: [ "adaptive_blur", "adaptive_resize", "adaptive_sharpen", "adjoin", "affine", "alpha", "annotate", "antialias", "append", "apply", "attenuate", "authenticate", "auto_gamma", "auto_level", "auto_orient", "auto_threshold", "backdrop", "background", "bench", "bias", "bilateral_blur", "black_point_compensation", "black_threshold", "blend", "blue_primary", "blue_shift", "blur", "border", "bordercolor", "borderwidth", "brightness_contrast", "cache", "canny", "caption", "channel", "channel_fx", "charcoal", "chop", "clahe", "clamp", "clip", "clip_path", "clone", "clut", "coalesce", "colorize", "colormap", "color_matrix", "colors", "colorspace", "colourspace", "color_threshold", "combine", "combine_options", "comment", "compare", "complex", "compose", "composite", "compress", "connected_components", "contrast", "contrast_stretch", "convert", "convolve", "copy", "crop", "cycle", "deconstruct", "define", "delay", "delete", "density", "depth", "descend", "deskew", "despeckle", "direction", "displace", "dispose", "dissimilarity_threshold", "dissolve", "distort", "dither", "draw", "duplicate", "edge", "emboss", "encoding", "endian", "enhance", "equalize", "evaluate", "evaluate_sequence", "extent", "extract", "family", "features", "fft", "fill", "filter", "flatten", "flip", "floodfill", "flop", "font", "foreground", "format", "frame", "function", "fuzz", "fx", "gamma", "gaussian_blur", "geometry", "gravity", "grayscale", "green_primary", "hald_clut", "highlight_color", "hough_lines", "iconGeometry", "iconic", "identify", "ift", "illuminant", "immutable", "implode", "insert", "intensity", "intent", "interlace", "interline_spacing", "interpolate", "interpolative_resize", "interword_spacing", "kerning", "kmeans", "kuwahara", "label", "lat", "layers", "level", "level_colors", "limit", "limits", "linear_stretch", "linewidth", "liquid_rescale", "list", "loader", "log", "loop", "lowlight_color", "magnify", "map", "mattecolor", "median", "mean_shift", "metric", "mode", "modulate", "moments", "monitor", "monochrome", "morph", "morphology", "mosaic", "motion_blur", "name", "negate", "noise", "normalize", "opaque", "ordered_dither", "orient", "page", "paint", "pause", "perceptible", "ping", "pointsize", "polaroid", "poly", "posterize", "precision", "preview", "process", "quality", "quantize", "quiet", "radial_blur", "raise", "random_threshold", "range_threshold", "red_primary", "regard_warnings", "region", "remote", "render", "repage", "resample", "resize", "resize_to_fill", "resize_to_fit", "resize_to_limit", "resize_and_pad", "respect_parentheses", "reverse", "roll", "rotate", "sample", "sampling_factor", "saver", "scale", "scene", "screen", "seed", "segment", "selective_blur", "separate", "sepia_tone", "shade", "shadow", "shared_memory", "sharpen", "shave", "shear", "sigmoidal_contrast", "silent", "similarity_threshold", "size", "sketch", "smush", "snaps", "solarize", "sort_pixels", "sparse_color", "splice", "spread", "statistic", "stegano", "stereo", "storage_type", "stretch", "strip", "stroke", "strokewidth", "style", "subimage_search", "swap", "swirl", "synchronize", "taint", "text_font", "threshold", "thumbnail", "tile_offset", "tint", "title", "transform", "transparent", "transparent_color", "transpose", "transverse", "treedepth", "trim", "type", "undercolor", "unique_colors", "units", "unsharp", "update", "valid_image", "view", "vignette", "virtual_pixel", "visual", "watermark", "wave", "wavelet_denoise", "weight", "white_balance", "white_point", "white_threshold", "window", "window_group" ]
#track_variants (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 363
mattr_accessor :track_variants, default: false
#unsupported_image_processing_arguments (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 354
mattr_accessor :unsupported_image_processing_arguments
#urls_expire_in (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 357
mattr_accessor :urls_expire_in
#variable_content_types (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 59
mattr_accessor :variable_content_types, default: []
#variant_processor (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 50
mattr_accessor :variant_processor, default: :mini_magick
#verifier (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 49
mattr_accessor :verifier
#video_preview_arguments (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 365
mattr_accessor :video_preview_arguments, default: "-y -vframes 1 -f image2"
#web_image_content_types (rw)
[ GitHub ]# File 'activestorage/lib/active_storage.rb', line 60
mattr_accessor :web_image_content_types, default: []