Search code examples
ruby-on-railsdevise

Installing Devise: `PG::UndefinedTable: ERROR: relation "users" does not exist`


Here's what I did successfully to install Devise:

  • I put in the devise gem
  • Ran bundle install
  • Installed devise with rails generate devise:install
  • Ran rake db:migrate (successfully) just to be safe

Now when I try to do rails generate devise User I get the following error:

== 20190915133638 AddDeviseToUsers: migrating =================================
-- change_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedTable: ERROR:  relation "users" does not exist
: ALTER TABLE "users" ADD "email" character varying DEFAULT '' NOT NULL

I tried this adding a few custom fields to the devise migration, but then again with the autogenerated migration and got the same result either way.

Can anyone see how I'm getting this error? I've tried rake db:reset db:create db:migrate but to no avail.


Solution

  • Did you have a User model before? It seems that devise thought that too and it's trying to add its columns to a non-existent User model.

    This is what I would do...

    1. Run rails db:drop
    2. Delete db/schema.rb file.
    3. Delete db/migrate/20190915133638_add_devise_to_users.rb
    4. Run rails generate devise:install again
    5. Run rails db:migrate

    EDIT

    If the previous steps didn't work then try to create a users table before devise's migration.

    For this follow these steps:

    1. rails g model User
    2. Change the name of the migration file so it will be executed right before the AddDeviseToUsers migration.
    3. Run rails db:migrate