Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find total size of user attachments in active storage

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?

like image 902
Fahad Avatar asked May 27 '20 17:05

Fahad


People also ask

How do I delete active storage 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.

Where are active storage files stored?

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!

What is Activestorage?

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.

How does active storage work in Rails?

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.


1 Answers

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)
like image 54
mechnicov Avatar answered Sep 20 '22 23:09

mechnicov