Rails can't undelete a dropped or overwritten database by itself—there is no rails db:undelete command. What Rails gives you is a structured way to find out what was lost, stop further writes, and rebuild the schema and data from backups, schema files, migrations, seeds, or partial dumps. The key condition: recovery is only as good as the most recent intact backup or export that exists outside the live database. Everything below is an ordered set of actions, from the safest reversible checks to the point where you should stop and call a database or hosting professional.
This guide assumes a conventional Ruby on Rails application (any modern 6.x, 7.x, or 8.x release) using PostgreSQL, MySQL, or SQLite, deployed either on a platform-as-a-service or on your own servers. Exact commands differ by adapter and host, so where a value is environment-specific I say what to check rather than guessing it.
First: Understand What "Deleted" Actually Means
Before touching anything, classify the incident. "Deleted database" in Rails conversations usually means one of five different things, and each has a different recovery path:
1: A dropped database or schema (e.g., DROP DATABASE, or a platform "destroy database" action). The whole container of tables is gone. 2: Tables truncated or dropped inside an existing database. The database exists; data is missing. 3: Rows deleted by a bug, a bad console session, or a runaway migration (DELETE FROM ... without a where clause, Model.delete_all in a task, or a dependent: :destroy cascade). 4: The local development database wiped by rails db:drop, db:reset, db:schema:load, or db:prepare behaving unexpectedly. This is common and usually the least costly. 5: A production data file deleted or corrupted at the storage layer, for example a managed database volume removed, or a SQLite file deleted on disk.
Your recovery options shrink as you move down that list away from backups and toward raw storage. The most important early decision is: is there a restorable backup, and how recent is it? If the answer is yes, most of this article is about restoring quickly and safely. If the answer is no, you're in reconstruction territory: schema from source control, data from exports, logs, replicas, or downstream systems.
A second early decision: is the application still writing to a live database that shares any state with the lost one (for example, a replica, a cached feed, or a search index)? If so, freeze writes before anything else so the situation doesn't change under you.
Step 1: Stop Writes and Freeze the Blast Radius
This is reversible and always first. Anything that continues writing makes recovery harder: new rows can collide with restored primary keys, background jobs can re-trigger deletions, and caches can mask which data is actually gone.
Actions, in order:
1: Put the app into maintenance or read-only mode if your platform supports it. On Heroku-style platforms this is a maintenance-mode toggle; on Kubernetes, scale the web and worker deployments to zero replicas; on a single server, stop the application service (for example systemctl stop puma or your process manager's equivalent). 2: Pause background workers and schedulers. A queued job that deletes expired records can re-run against a restored copy. Pause Sidekiq, Solid Queue, Delayed Job, or whatever your app uses, and disable cron or scheduler entries that touch data. 3: Revoke or rotate credentials if the deletion looks accidental by a person or script. This prevents a retry loop from re-deleting data you restore. 4: Do not run rails db:migrate, db:reset, db:setup, or db:prepare yet. These can drop or recreate objects, and db:prepare in particular can load a schema that silently overwrites what remains. 5: Note the timestamp of when the deletion was noticed and, if you can find it, when it actually occurred. That window determines which backup to pick and how much data you'll need to re-enter or reconcile.
Success check: no application process is writing to the database, and you can point to the exact moment you froze writes. If you can't stop writes because it's a vendor-managed database you can't control, document that and move to backups immediately—restoring over a live, partial database can be worse than waiting.
Step 2: Identify Which Database and Which Environment
Rails makes it easy to confuse environments. A surprising number of "we deleted production" incidents are actually a misconfigured DATABASE_URL pointing a staging task at production, or a developer running a destructive rake task with RAILS_ENV unset.
Actions:
1: Read the connection config. Check config/database.yml, config/environments/*.rb, and any DATABASE_URL in the environment. In a Rails console or runner, ActiveRecord::Base.connection_db_config (Rails 6.1+) prints the adapter, database name, host, and whether it's the primary. Rails.env shows the environment. 2: Compare against what you expect. If Rails.env is development but the host is a managed production endpoint, you've found your problem—and possibly your safety net, because the real production data may be untouched. 3: Check whether the database actually exists. With PostgreSQL: psql "$DATABASE_URL" -c '\l' lists databases. With MySQL: mysql -e 'SHOW DATABASES;'. With SQLite, confirm the file path and that the file exists. If the database is missing entirely, you're in case 1 above.
Success check: you can state, in one sentence, which environment, host, and database name were affected. If you can't, stop—guessing here is how people restore the wrong dump into the wrong place.
Step 3: Inventory Backups and Choose a Recovery Point
This step determines almost everything that follows. Rails itself doesn't create backups; your hosting platform, your DBA practice, or a gem does. Look in each of these places, in roughly this order of reliability:
Managed database snapshots and point-in-time recovery. Most managed Postgres and MySQL services retain automated backups and, in paid tiers, allow restoring to an arbitrary second within a retention window (commonly 1–35 days, depending on plan—check your plan's actual retention). This is almost always the best option: it restores a consistent snapshot of the whole database. Platform-level backups for platforms that bundle a database (for example, a hosted Postgres add-on with its own backup schedule). Your own pg_dump / mysqldump jobs, whether run from cron, a rake task, or CI. Check where the files land (object storage like S3 or GCS, a backup bucket) and whether they're encrypted and test-restored. Database replicas or read replicas. A lagging replica may still hold data from before the deletion. Promoting or dumping from a replica is a legitimate recovery source, but confirm its lag first—it might already have the deletion. Logical exports or data warehouse copies. Analytics pipelines, CDC streams, or nightly CSV exports often retain a usable copy. Developer machines and staging databases. A colleague's local development database, or staging seeded from a recent production dump, may hold most of the data.
For each candidate, record: the timestamp of the backup, whether it's a full database or partial, whether it's consistent (a snapshot is; a pg_dump running while writes continue is transactionally consistent for Postgres but may be behind), and whether you've ever successfully restored from that source before.
Pick the most recent backup that predates the deletion by more than your longest transaction, and note how much data you'll lose—the gap between the backup timestamp and the deletion time. That gap is your data-loss window, and it drives Step 6.
Stop condition: if no backup exists and the data is genuinely gone from storage, professional data-recovery services or your hosting provider's support are the only paths left for the raw bytes. Don't keep experimenting on the live volume; every mount and write reduces the chance of forensic recovery.
Step 4: Restore Safely—Never Over the Only Copy
The cardinal rule: restore into a new, separate database first. Restoring directly over the affected database overwrites any residual data and destroys your ability to compare or recover fragments.
The general sequence, adapted per adapter:
PostgreSQL (managed snapshot or pg_dump)
1: Create a fresh database: createdb myapp_recovery (or via your platform's UI). 2: If you have a custom-format dump: pg_restore --no-owner --no-privileges -d myapp_recovery backup.dump. If it's a plain SQL dump: psql -d myapp_recovery -f backup.sql. 3: If you're restoring a platform snapshot, restore it to a new instance/endpoint, then point a staging Rails environment at it.
MySQL / MariaDB
1: CREATE DATABASE myapp_recovery; 2: mysql myapp_recovery < backup.sql. For large dumps, --single-transaction at dump time and --quick help; expect a long restore for big datasets.
SQLite
1: Copy the backup file to a new path: cp backup.sqlite3 recovery.sqlite3. SQLite databases are single files, so "restore" is a file copy—just never copy over the live file while the app has it open.
Then, validate before trusting:
Run rails db:version against the recovery database with DATABASE_URL pointed at it; the schema version should match a migration that existed at backup time. Run rails runner against it to count key tables: User.count, Order.where(created_at: ... ).count, and spot-check recent records. Check that the restore completed without errors. pg_restore reports errors for missing roles or extensions; those are often harmless but should be reviewed, not ignored.
Success check: the recovery database answers basic queries, row counts look plausible, and the newest timestamps are consistent with the backup date.
Step 5: Reconstruct What Rails Can Rebuild Without a Backup
If you have no usable data backup but retain source control and some data sources, Rails can rebuild the schema deterministically. This is the common development-database and early-stage-production case.
Schema from migrations or schema.rb
1: Create an empty database: rails db:create. 2: Load the schema: rails db:schema:load (or db:structure:load for structure.sql users). This is faster and more faithful than replaying every migration from scratch. 3: Verify: rails db:version reports the current schema version, and rails db:abort_if_pending_migrations exits cleanly. 4: If you must replay migrations (for example, data migrations that seed reference rows), rails db:migrate on the empty database does it in order.
Reference and seed data
rails db:seed re-creates whatever db/seeds.rb defines—countries, plans, roles, categories. Seeds are code, so they're versioned and reliable, but they only cover what someone chose to put there. They won't restore customer records.
Recovering rows from logs, exports, and downstream systems
This is where reconstruction gets real. Useful sources:
Application logs that logged request payloads (rarely advisable in production for privacy reasons, but sometimes present). Database write-ahead logs or binlogs if your provider exposes them (Postgres WAL archiving, MySQL binlogs). Replaying individual transactions is advanced DBA work; it's where you call in a professional. Downstream systems that received copies: email providers with sent-message records, payment processors with transaction histories, CRM or analytics stores, and search indexes you sync from Rails. You can often rebuild a surprisingly large fraction of rows by pulling from these. Rails' own soft state: if you use a gem like paper_trail (versioning) or paranoia/discard (soft deletes), deleted rows may still exist in a versions table or a deleted_at column—check before assuming loss. Note that delete_all in Rails skips callbacks, so soft-delete gems won't intercept it.
A worked estimate for sizing reconstruction: suppose the app has 50,000 orders and the backup is 3 days old, with roughly 400 orders/day. Your data-loss window is about 1,200 orders. If payment records are exportable from your processor and email receipts exist, you may recover most of those; plan reconciliation as a bounded task of roughly 1,200 records, not an open-ended one.
Success check: after loading schema and seeds, rails db:setup-style checks pass, and you have a written list of which tables are empty and why.
Step 6: Bring the App Back on the Right Database
Once the recovery database is verified, point the app at it deliberately and in stages.
1: Update the connection config for the target environment—DATABASE_URL, config/database.yml, or the platform's environment variable. Do this in one place and record the change. 2: Run a read-only smoke test. Deploy or restart staging pointed at the recovery database; log in, load a dashboard, run a representative query. Compare a few key counts against the backup validation from Step 4. 3: Deal with pending migrations. If schema.rb at HEAD is newer than the backup, rails db:migrate brings the recovered database up to current schema. Plot this: rails db:migrate:status shows which migrations are up/down. Run migrations on a copy first if they're destructive. 4: Reconcile the data-loss window. If you recovered from a backup older than the deletion, decide how to fill the gap—replay from exports or downstream sources, or accept the loss and notify affected users. For row-level gaps, an INSERT ... ON CONFLICT DO NOTHING (Postgres) or INSERT IGNORE (MySQL) import keyed on primary keys is the standard idempotent approach. 5: Re-enable writes and workers gradually. Notify the team, restore traffic, then unpause jobs. Watch error rates and database connections.
Success check: the app serves reads and writes without errors, migration status is clean, and the reconciliation list from Step 6 item 4 is closed or explicitly accepted.
Step 7: Prevent the Same Deletion From Happening Again
This step is the one people skip, and it's the cheapest part of recovery. Short, concrete measures that fit a Rails codebase:
Block destructive console commands in production. Common patterns: guard delete_all/destroy_all behind an explicit environment check, add a Rails.env.production? guard to rake tasks that touch data, and restrict access to the production console. Require a where clause. In PostgreSQL you can make a rule or trigger that raises on DELETE without a where clause; many teams instead add a soft-delete pattern. Either way, rails runner 'Model.delete_all' should be hard to run by accident. Automate and test backups. Schedule pg_dump/mysqldump to object storage, encrypt them, and—critically—run a monthly test restore into a scratch database. An untested backup is a guess. Verify managed backup retention and PITR. Know your plan's retention window and whether point-in-time recovery is enabled; a common failure is assuming PITR exists on a tier that doesn't include it. Keep schema.rb in source control and load it in CI so the schema is always recoverable from code.
These measures don't recover a single row, but they're what make the next incident a 20-minute restore instead of a multi-day reconstruction.
Failure Modes That Change the Plan
A few situations deserve their own handling because the standard playbook misleads:
The deletion happened inside a transaction that's still open. In an emergencies where a psql/mysql session is still connected and holding the transaction, rolling back immediately (ROLLBACK;) can recover everything, because the change was never committed. This is worth checking first if a console session is still alive. A dependent destroy cascade ran. has_many :children, dependent: :destroy deletes children when a parent is destroyed. The children are gone too, and the cascade direction tells you which tables to rebuild first. The "deleted" data was actually just a bad query or scope. Before any restore, confirm with EXPLAIN or a Model.unscoped query that rows really are missing rather than hidden by a default scope, a deleted_at filter, or a misconfigured search index. This is the cheapest possible win and should be checked in Step 2. The database is encrypted or the backup keys are missing. A restored backup without its encryption key is a brick. Confirm key availability before starting a restore. You're on a platform with no direct database access. Restores are done through the platform's UI or API; follow its documented restore flow and don't improvise.
When to Stop and Call a Professional
Stop working on the system and escalate to a database or hosting professional when any of the following is true: the data exists only on raw storage (no logical backup), you need to replay write-ahead or binary logs transaction by transaction, the deletion involved a schema change that broke foreign key integrity across many tables, or you're a regulated environment where the data must be accounted for precisely. Continuing to run experiments against the only copy of the data is the one thing that reliably makes an incident worse. Hosting support and specialized data-recovery services are the appropriate routes, and they're honest about which cases are unrecoverable.
The order matters more than any single command: freeze writes, identify the environment, inventory backups, restore to a new database, validate, rebuild schema and seeds if no backup exists, then switch the app over and close the data-loss gap. Rails supplies the schema and seed machinery; backups supply the data; the discipline of never restoring over the only copy is what turns a disaster into a routine restore.