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
I encountered this error, and upon my research, found out that one of the reasons for PG undefinedtable error relation users does not exist error is:
This error is a migration error. You may have created new model with some database attributes. After creating model you have to migrate attributes to your rails app schema.
If you are using local machine, for development, you can use command
rake db:migrate
If you're using heroku
heroku run rake db:migrate
Your test database is not ready for rspec.
Prepare your test database for rspec to fix this error
RAILS_ENV=test rake test:prepare
It will drop, create and add migrations to your test database
In case rake task is aborted with message like 'PG::Error: ERROR: database "[your_db_test]" is being accessed by other users' execute this one
RAILS_ENV=test rake db:migrate