DEV Community

Josua Schmid
Josua Schmid

Posted on • Edited on

1

Sum ActiveStorage::Blob byte_size

You may think to sum up the size all ActiveStorage files, you could simply execute the following query:

ActiveStorage::Blob.sum(:byte_size)
Enter fullscreen mode Exit fullscreen mode

But this may produce numbers too large for the resulting column type:

ActiveRecord::RangeError (TinyTds::Error: Arithmetic overflow error converting expression to data type int.)
Enter fullscreen mode Exit fullscreen mode

The solution is to cast:

ActiveStorage::Blob.connection.exec_query(
  'SELECT SUM(CAST(byte_size AS BIGINT)) from active_storage_blobs'
).first
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more