Drop production database in Rails

Kavita Jadhav
2 min readJun 25, 2022
https://cdn.memegenerator.es/imagenes/memes/full/18/98/18987948.jpg

Rails provides commands to create the database, update schema definition, and seed application details in the database. It also provides the command to drop the database.

Drop database command can be used to drop the database in local or non-production environments when you want to recreate your database like below:

bin/rails db:drop RAILS_ENV=$environment_name

Have you ever wondered, what if you accidentally run the above command in the production environment? Will you lose all of your production data?

The answer is No, unless you run the below command:

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

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

When commands are run against the database, rails will check if the environment is in production to prevent data mishaps. When the environment is production, the command will fail with the 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 issues.

Happy Coding!

--

--