PG undefinedtable error relation users does not exist

At first, you shall detach all connections out of database. By default you use the development environment. Then try to reset database with the following:

rake db:reset

The rake db:reset task will drop the database and set it up again. This is functionally equivalent to rake db:drop db:setup.

This is not the same as running all the migrations. It will only use the
contents of the current schema.rb file. If a migration can’t be rolled back,
rake db:reset may not help you. To find out more about dumping the schema see
Schema Dumping and You section. Rails Docs

If the trick doesn’t help, drop the database, then re-create it again, migrate data, and if you have seeds, sow the database:

rake db:drop db:create db:migrate db:seed

or in short way (since 3.2):

rake db:migrate:reset db:seed

Since db:migrate:reset implies drop, create and migrate the db. Because the default environment for rake is development, in case if you see the exception in spec tests, you should re-create db for the test environment as follows:

RAILS_ENV=test rake db:drop db:create db:migrate

or with just loading the migrated scheme:

RAILS_ENV=test rake db:drop db:create db:schema:load

In most cases the test database is being sowed during the test procedures, so db:seed task action isn’t required to be passed. Otherwise, you shall to prepare the database (this is deprecated in Rails 4):

rake db:test:prepare

and then (if it is actually required):

RAILS_ENV=test rake db:seed

On newer versions of Rails the error ActiveRecord::NoEnvironmentInSchemaError may be risen, so just prepend the tasks with a database environment set task: db:environment:set:

RAILS_ENV=test rake db:environment:set db:drop db:create db:migrate

Leave a Comment