---
title: Purge unattached ActiveStorage::Blobs
author: Victor Cobos
tags: Rails, Active Storage
published_at: '2024-03-09T18:43:00+01:00'
updated_at: '2024-07-24T11:30:00+02:00'
canonical_url: https://www.dotruby.com/articles/purge-unattached-activestorage-blobs
---

# Purge unattached ActiveStorage::Blobs

Keep your storage clean by purging unattached ActiveStorage::Blobs. This guide walks you through setting up a rake task to automatically remove blobs that are no longer linked to records, saving space and reducing costs.

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

```ruby
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.
