I'm using Rails 6. How to get the total size of user attachments in active storage?
======
Update:
If I have User A and User B
How to get the total size of User A attachments?
To remove an attachment from a model, call purge on the attachment. If your application is set up to use Active Job, removal can be done in the background instead by calling purge_later . Purging deletes the blob and the file from the storage service.
By default in the development environment, Active Storage stores all uploaded images on your local disk in the storage subdirectory of the Rails application directory. That's the file you uploaded!
Active storage is an inbuilt gem in Rails that developers widely use to handle file uploads. Combined with the encrypted credentials feature in the latest releases of Rails, active storage is a safe and easy method to upload, serve, and analyze files onto cloud-based storage services as well as local storage.
Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.
If you want to get size of all attachments associated with some record (e.g. user = User.first
) you can use this:
ActiveStorage::Attachment.where(record: user).map(&:byte_size).sum
or more efficient with such query
ActiveStorage::Attachment.joins(:blob).where(record: user).sum(:byte_size)
or like this
ActiveStorage::Blob.
joins(:attachments).
where(active_storage_attachments: { record_id: user.id, record_type: user.class.name }).
sum(:byte_size)
For example this user has_many_attached :images
In this case you can get size only of all images of this user as:
user.images.map(&:byte_size).sum
or more efficient with such query
user.images.joins(:blob).sum(:byte_size)
or like this
user.images_blobs.sum(:byte_size)
Using include ActionView::Helpers::NumberHelper
you can convert byte size (integer) to human format:
number_to_human_size(size_of_all_attachments)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With