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?
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)