From f4c51e8660bf1771268d45325fff8378eb90698e Mon Sep 17 00:00:00 2001 From: Steve Polito Design Date: Thu, 14 Jan 2021 09:51:37 -0500 Subject: [PATCH] Add section on how to purge unattached uploads. --- guides/source/active_storage_overview.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index 116b45ba29..1e0dccb542 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -959,6 +959,8 @@ class Uploader { } ``` +NOTE: Using [Direct Uploads](#direct-uploads) can sometimes result in a file that uploads, but never attaches to a record. Consider [purging unattached uploads](#purging-unattached-uploads). + Discarding Files Stored During System Tests ------------------------------------------- @@ -1035,3 +1037,19 @@ If you need to support a cloud service other than these, you will need to implement the Service. Each service extends [`ActiveStorage::Service`](https://github.com/rails/rails/blob/main/activestorage/lib/active_storage/service.rb) by implementing the methods necessary to upload and download files to the cloud. + +Purging Unattached Uploads +-------------------------- + +There are cases where a file is uploaded but never attached to a record. This can happen when using [Direct Uploads](#direct-uploads). You can query for unattached records using the [unattached scope](https://github.com/rails/rails/blob/8ef5bd9ced351162b673904a0b77c7034ca2bc20/activestorage/app/models/active_storage/blob.rb#L49). Below is an example using a [custom rake task](command_line.html#custom-rake-tasks). + +```ruby +namespace :active_storage do + desc "Purges unattached Active Storage blobs. Run regularly." + task purge_unattached: :environment do + ActiveStorage::Blob.unattached.where("active_storage_blobs.created_at <= ?", 2.days.ago).find_each(&:purge_later) + end +end +``` + +WARNING: The query generated by `ActiveStorage::Blob.unattached` can be slow and potentially disruptive on applications with larger databases.