Search code examples
ruby-on-railsrails-activestorage

Can you _remove_ a variant from ActiveStorage?


Using ActiveStorage in Rails, variants are added "on demand" as you create them. They are now persisted in some storage (disk, S3, google cloud, etc).

If you realize some variants are un-needed after all and change your code to not invoke them... I think they'll still be sitting persisted in storage.

How does one clean these up, so they're not taking up storage space? I can't find any ActiveStorage API to remove variants.


Solution

  • You can delete a file from ActiveStorage services (disk, s3 etc.) with its key . And a variant's key is identified by its blob and transformation. Therefore you can delete a specific variant like this:

    avatar = user.avatar
    variant = avatar.variant(resize: '100x100')
    avatar.service.delete(variant.key)