Pre-defined ActiveStorage variants in Rails 7
April 4, 2022Rails 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;
developer of Roomies.com, myRent.co.nz, High School Notes & StudentVIP.com.au.
