Drop production database in Rails

Rails provides commands to create, migrate database, seed application details in the database. It also provides the command to drop database.

Drop database command is used to drop database in local or non production environments when you want to recreate your database. Command is as below:

bin/rails db:drop RAILS_ENV=$environment_name

Have you ever wondered, what if you accidentally run above command against production environment? Will you loose all of your production data?

Answer is No, unless you run below command:

bin/rails db:drop RAILS_ENV=production DISABLE_DATABASE_ENVIRONMENT_CHECK=1

Rails create an internal table ar_internal_metadata which contains environment variables along with values and timestamp. When the database schema is generated, a new row for environment is added in the ar_internal_metadata table with key as environment and value as $environment_name.

When commands are run against the database, rails will check if environment is production to prevent data mishaps. When environment is production, command will fail with below message:

rake aborted!
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your 'production' database.
If you are sure you want to continue, run the same command with the environment variable:
DISABLE_DATABASE_ENVIRONMENT_CHECK=1

If you still want to proceed with the command then you can make the command work by appendingDISABLE_DATABASE_ENVIRONMENT_CHECK=1 in the command

Hope this will help you when you face related issue.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kavita Jadhav

Kavita Jadhav

Application Developer @ ThoughtWorks Technologies