How to avoid ActiveRecord::EnvironmentMismatchError on "rails db:drop"

After loading a staging dump into development, you might get an ActiveRecord::EnvironmentMismatchError when trying to replace the database (like rails db:drop, rails db:schema:load).

$ rails db:drop
rails aborted!
ActiveRecord::EnvironmentMismatchError: You are attempting to modify a database that was last run in `staging` environment.
You are running in `development` environment. If you are sure you want to continue, first set the environment using:

        bin/rails db:environment:set RAILS_ENV=development

Starting with Rails 5, the ar_internal_metadata database table was introduced:

> SELECT * FROM ar_internal_metadata;
     key     |  value  |         created_at         |         updated_at         
-------------+---------+----------------------------+----------------------------
 environment | staging | 2017-06-01 08:30:00.123456 | 2017-06-01 08:30:00.123456

You can do what Rails suggests, and change the stored environment:

RAILS_ENV=development rails db:environment:set

For parallel tests:

rake parallel:rake[db:environment:set]

Then re-run your command.

Or, if you are absolutely certain that everything is correct, set an environment variable to run your command but disable that check.

DISABLE_DATABASE_ENVIRONMENT_CHECK=1 rails db:drop
Arne Hartherz over 4 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more