Database

Resolving Rails Active Storage Missing Attachments Migration

BLUF (Bottom Line Up Front): A botched file migration often leaves orphan records in the active_storage_attachments table pointing to non-existent active_storage_blobs or missing physical files on S3. This destroys data consistency and causes ActiveStorage::FileNotFoundError crashes in production. The solution is executing a forensic audit script to identify and purge or repair broken links.

Phase 1: Identifying Data Corruption

When migrating from legacy systems, network timeouts or script errors can result in an Attachment record being saved, while the underlying Blob or the physical S3 file fails to upload.

Synthetic Engineering Context: The Crash

Your error tracking system (e.g., Sentry) lights up with errors when a view attempts to render an image:

ActionView::Template::Error (ActiveStorage::FileNotFoundError)
1: <%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>

The database believes the file exists, but the storage service returns a 404.

Phase 2: The Forensic Audit Script

To restore blob integrity, you must scan the database and cross-reference it with the storage provider.

# lib/tasks/audit_storage.rake
namespace :storage do
  desc "Detect orphan records and missing files in Active Storage"
  task audit: :environment do
    broken_attachments = []

    ActiveStorage::Attachment.find_each do |attachment|
      # Check 1: Does the blob exist in the DB?
      if attachment.blob.nil?
        broken_attachments << { id: attachment.id, reason: "Missing Blob DB Record" }
        next
      end

      # Check 2: Does the physical file exist on the service (e.g., S3)?
      begin
        unless attachment.blob.service.exist?(attachment.blob.key)
          broken_attachments << { id: attachment.id, reason: "Missing Physical File" }
        end
      rescue => e
        broken_attachments << { id: attachment.id, reason: "Service API Error: #{e.message}" }
      end
    end

    puts "Audit Complete. Found #{broken_attachments.count} broken records."
    # Log the broken_attachments array for manual review or automated cleanup
  end
end

Once identified, you can safely call attachment.purge on the broken records to clear the database inconsistencies.

Need Help Stabilizing Your Legacy App? Data consistency in Active Storage is critical. If your application is crashing due to missing files or corrupted blobs, our team at USEO can run deep forensic audits and repair your storage architecture.

Contact us for a Technical Debt Audit