Purge unattached ActiveStorage::Blobs.

Published on March 09, 2024
Written by Victor Cobos

When's the last time you cleaned up those ActiveStorage::Blobs hanging around without attachments?

namespace :active_storage do
  desc "Purges unattached ActiveStorage::Blobs"
  task purge_unattached: :environment do
    ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)
  end
end

If you're handling direct uploads consider running this rake task periodically to keep the cloud bucket clean and avoid paying for storage that's not being used.

Subscribe to get future articles via the RSS feed .