Dwight Watson's blog

Pre-defined ActiveStorage variants in Rails 7

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

Rails 7 introduced a new feature to pre-define your ActiveStorage variants to allow re-use throughout your app. Unfortunately one of the top blog posts on Google doesn't show how to use it correctly - demonstrating the original proposed syntax instead of the one that shipped.

Simply speaking, you can pop a block after the ActiveStorage attachment and then create named variants to use where required.

class User < ApplicationRecord
has_one_attached :avatar do |attachable|
attachable.variant :thumbnail, resize: "100x100"
end

Then you can provide the named symbol when referencing the attachment.

image_tag user.avatar.variant(:thumbnail)

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.