Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 761
jrochkind Avatar asked Sep 18 '18 14:09

jrochkind


People also ask

How ActiveStorage works?

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.

What is Active storage blob?

A blob is a record that contains the metadata about a file and a key for where that file resides on the service. Blobs can be created in two ways: Subsequent to the file being uploaded server-side to the service via create_after_upload!.


2 Answers

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)
like image 100
wesley6j Avatar answered Oct 06 '22 00:10

wesley6j


If the cost of generating all variants again is acceptable or if you need to invalidate most variants, then you can simply delete the variants folder. Rails will generate the variants again when needed.

like image 20
collimarco Avatar answered Oct 06 '22 01:10

collimarco