You can get a deleted file back in Rails only if a copy still survives somewhere outside the deleted path: Active Storage tracks the blob and the storage service may keep it, your operating system's trash still holds a locally deleted file, version control has the last committed copy, or a backup captured it. If the file was truly overwritten and no copy exists, Rails itself cannot reconstruct the bytes — Rails is application code, not a file-recovery layer.

The single most important condition to establish first is which kind of deletion happened. A File.delete call on a local disk, an Active Storage purge, a file removed by a deploy script, and a database row deleted without touching storage are four different problems with four different recovery paths. Readers usually ask this question after a panicked moment in production, so the order below moves from fastest and most reversible checks to heavier recovery, with the failure cases that decide whether you stop or keep going.

Identify What Was Actually Deleted Before Reaching for a Tool

Recovery succeeds or fails on classification, so spend two minutes naming the deletion type. Guessing wrong wastes the most time on the least promising path.

Deletion type Where the file lives Recoverable by First check
File.delete / FileUtils.rm on app server Local disk of that server OS trash (only if rm was not used), backup, overlay snapshot Is the server containerized? If yes, the file is gone with the container
Active Storage purge / purge_later Disk, S3, GCS, Azure service Service-side versioning or soft delete, backup Has the blob row been destroyed from active_storage_blobs?
Database row deleted, file untouched Storage service still has the object Recreate the record, reattach by key Does the blob still exist but the attachment row is gone?
Deploy, git clean, or build step Working tree Git history, CI artifact cache Was the file ever committed?

Two facts drive everything downstream. First, plain File.delete in Ruby does not use the operating system trash — it unlinks the file immediately, so a Mac's Trash folder or Linux desktop trash will not help unless a human deleted it through the desktop. Second, Active Storage on cloud services deletes the underlying object when you purge, and object stores do not provide a recycle bin by default.

Recover a File Deleted from Local Disk on the Server

Local-disk deletion is the most common version of this question, and the recovery window depends on what the file system and hosting layer preserved.

If your Rails app runs in a container or an ephemeral instance, stop here: the writable layer vanishes on redeploy or restart, and no local recovery is possible. Confirm with df -h and check whether the file path sits on a mounted volume. Files on a mounted volume survive container replacement; files in the layer do not.

For a long-lived VM with a real file system, take these in order:

1: Check whether the file was deleted through a desktop session or an app that respects the trash. On a Linux server with trash-cli installed, run trash-list and trash-restore. On macOS, look in ~/.Trash for the deploying user. A plain Ruby File.delete skips both. 2: Check for open file handles before anything else overwrites the blocks. Run lsof +L1 and look for lines with a link count of 1 — a deleted file still open by a process can be copied back out. This works while the process holds the descriptor, so act before restarting the app. 3: Check file-system snapshots if the host provides them (LVM, ZFS, btrfs, cloud volume snapshots). Restore the single path rather than the whole volume where the platform allows it. 4: Stop writing to the affected volume, then use a recovery utility that matches the file system — extundelete or ext4magic for ext4, testdisk/photorec for broader cases. Success drops sharply once new writes reuse the inodes.

As a success check, the restored file should open, match the expected size, and pass whatever integrity check your app performs. If lsof +L1 returns nothing and there are no snapshots or backups, treat recovery as unlikely and switch to reconstructing the file from upstream sources or asking the user to re-upload it.

Trace an Active Storage File Through the Blob and the Storage Service

Active Storage keeps metadata in two tables — active_storage_blobs (the file itself, key, checksum) and active_storage_attachments (the link to your record) — and the bytes live in the configured service. Recovery means finding a surviving copy at either layer.

Start in the Rails console with the record's ID if it still exists, or the blob key if you have it from logs:

ActiveStorage::Blob.find_by(key: "the-key") tells you whether the metadata survived. ActiveStorage::Attachment.where(record_type: "User", record_id: 42) shows attachments still linked to a record. ActiveStorage::Blob.unattached lists blobs with no attachment — a common rescue when an attachment row was deleted but the blob was not purged.

If the blob row exists and points to a file on the Disk service, the object is at the path returned by blob.service.path_for(blob.key), typically under storage/ in the app root in development or a configured root in production. Check that path directly; if the file is there, reattaching is enough: record.avatar.attach(blob) in modern Rails accepts an existing blob.

If the blob was purged from a cloud service, Rails cannot undo it, but the service might. S3 versioning, if enabled on the bucket, lets you restore the prior object version. Google Cloud Storage offers Object Versioning and soft delete; Azure Blob Storage offers soft delete and blob versioning. Each is a bucket-level or account-level setting you must have enabled before the deletion, which is the key limitation. Check the service's console for the object key — Active Storage uses the blob key as the object name — and restore from the version list if any versions exist.

For production data at rest on disk, the blob's checksum field lets you verify a recovered file: ActiveStorage::Blob.find_by(key: key)&.checksum compared against a fresh MD5 of the candidate file confirms you restored the right bytes.

Use Version Control and Editor History for Source Files

When the "deleted file" is code, a migration, a config file, or a fixture rather than a user upload, version control is the highest-yield path and almost always succeeds.

If the file was ever committed, git log --diff-filter=D --name-only -- path/to/file finds the commit that deleted it, and git checkout ^ -- path/to/file restores it from the commit before deletion. Use git log --all -- path/to/file if the deletion happened on a branch you have since left. An untracked file that was still staged can be recovered with git fsck --lost-found, which writes dangling blobs under .git/lost-found/; inspect them with git show . Editor local history is a real fallback: VS Code keeps timeline entries under its workspace storage, JetBrains IDEs keep Local History accessible from the right-click menu, and Vim's .swp files or Emacs autosave files (#file#) can hold unsaved content.

Success check: the restored file builds, passes tests, and its content diff against the expected version is empty. If git log --all shows nothing, the file was never tracked, and version control cannot help — move to backups.

Recover Database Rows With Point-in-Time Restore, Then Reattach Files

Sometimes the file on storage survived and only the database row vanished. In that case the recovery is a database restore, and the file layer needs no action.

PostgreSQL supports point-in-time recovery when write-ahead logging archiving is configured; you replay to a timestamp just before the delete. MySQL's binary log enables equivalent point-in-time recovery. Both require that the operator set this up in advance — if archiving was never enabled, the only option is the last full backup, and you lose everything after it.

The practical sequence is:

1: Restore the database to a staging instance, not production, and locate the deleted row. 2: Confirm the referenced storage object still exists by checking the blob key or disk path. 3: Re-insert the row or reattach the file to the existing record, then verify the attachment loads in the app.

A worked example makes the cost concrete. Suppose an automated cleanup job deletes attachments older than 90 days, and you discover on day 91 that a customer's contract PDF was wrongly matched. If your last full backup is nightly and you keep 30 daily backups, that file's metadata left the backup window before you noticed — the row is unrecoverable from backups alone, though the storage object may still exist if the purge failed. The lesson is that retention windows must exceed the longest realistic time to notice a mistake. Treat that as an illustrative model, not a fixed rule; set your own window from your worst realistic detection delay.

Choose the Right Recovery Route for Your Situation

Match the route to the evidence you found, rather than trying every tool.

Evidence found Route Realistic outcome
File in OS trash or trash-cli list Restore from trash Fast, certain
Open handle from lsof +L1 Copy out via /proc//fd/ on Linux Fast, certain while the process lives
File-system snapshot exists Single-path restore Fast, depends on snapshot age
Blob row exists, object on disk Reattach blob Fast, certain
Object on S3/GCS/Azure with versioning Service-side version restore Depends on versioning being enabled before deletion
Committed in Git Checkout from the deleting commit's parent Fast, certain
PostgreSQL/MySQL PITR configured Replay to before the delete Depends on WAL/binlog archiving
None of the above Recover from last full backup or rebuild Time cost proportional to backup age

Selection rule: pick the topmost row whose evidence you can actually verify in five minutes. Everything below it on the table costs more time and restores older data, so don't skip a cheap check to reach for a heavy one.

Prevent the Panic Next Time With Deletion You Can Reverse

Most recovery advice is wasted because the file is already gone. The durable fix is to make deletion soft by default and let a scheduled job do the hard delete later, after a review window.

Do this with Active Storage by removing the file from a record with purge_later replaced by your own deferred job that checks a grace flag, or by moving the object to a quarantine bucket or folder before purging. For disk files, move to a trash/ directory and sweep it after your retention window rather than calling File.delete. For database rows, add a deleted_at column and filter the default scope instead of issuing DELETE.

Three practical controls are worth naming: enable object-store versioning or soft delete on the bucket that holds production uploads; keep database backups on a schedule longer than your realistic detection window; and log every destructive operation with the record ID, blob key, and timestamp so a later recovery has a starting point.

A caution on order of operations: setting up versioning after the fact does not recover past deletions, and turning on soft delete on a bucket affects only deletions that happen after it is enabled. If a question is about a past incident, prevention does not help that incident.

Know the Hard Stops That Mean Stop Trying

Some situations will not be recoverable by any Rails-level technique, and continuing to write to the affected disk makes them worse.

Stop and switch strategies if the file was in a container's writable layer, if the storage service had neither versioning nor soft delete enabled at deletion time and the object was purged, or if the disk has been written to heavily since the deletion. In these cases, the recoverable artifact is not the original file but the nearest copy — a previous upload, a generated export, or an upstream source the user can re-send.

The other stop condition is scale. A single deleted file is a recovery problem; a mass deletion event (a buggy purge, a bad migration, a compromised credential) is an incident. At that point stop manual recovery, preserve the current state including logs, and involve whoever owns the infrastructure — or, for a breach-suspected credential compromise, your security contact — before changing anything. Guessing at fixes on a compromised or failing system can destroy the forensic trail you would need.

FAQ

Does rm in Ruby move the file to the Trash?

No. Ruby's File.delete and FileUtils.rm unlink the file directly, bypassing any desktop or server trash. Recovery from trash only applies when a human deleted the file through a tool that uses the trash.

Can I undelete an Active Storage blob after purge?

Only if the storage service itself kept a copy. Purging removes the blob row and asks the service to delete the object. S3 versioning, GCS Object Versioning, and Azure soft delete can preserve the object if they were enabled before the purge ran.

Will a database backup bring back the file itself?

It can bring back the database row and the blob metadata, but the bytes live in the storage service or on disk. Restoring the database does not restore disk files; it only restores the pointers and checksums you use to find or verify the file.

What's the fastest check when I don't know what happened?

Run lsof +L1 on the server and check whether the blob row still exists with ActiveStorage::Blob.find_by(key: ...). Those two checks take under a minute and divide the problem into "recoverable locally now" versus "needs a backup or service-side restore."