PG 无法定义的错误关系用户不存在

我之前看到过这个问题,但只是针对 Rspec。我还没有创建测试,因为它对我来说太先进了,但很快有一天我会!校对: P

当我尝试注册/登录到我的应用程序时,我得到了这个错误。我使用设计创建用户,也 Omniauth2登录与 谷歌

这就是错误

ActiveRecord::StatementInvalid at /users/auth/google_oauth2/callback
PG::UndefinedTable: ERROR:  relation "users" does not exist
LINE 5:              WHERE a.attrelid = '"users"'::regclass
^
:             SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"users"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum

我试过 rake db:migrate,但它已经被创建了: 在模式表中存在用户。以前有人得到过这个错误吗?

Yml

Config =/opt/local/lib/postgreql84/bin/pg _ config

development:
adapter: postgresql
encoding: unicode
database: tt_intraweb_development
pool: 5
username: my_username
password:


test:
adapter: postgresql
encoding: unicode
database: tt_intraweb_test
pool: 5
username: my_username
password:


production:
adapter: postgresql
encoding: unicode
database: tt_intraweb_production
pool: 5
username: my_username
password:
116182 次浏览

The most probable cause is that your rake is using different environment from database.yml than your webserver.

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

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

This is often caused by a bug in ActiveAdmin. Here's how to get around the bug:

If you're using ActiveAdmin, whichever table PG says doesn't exist, comment out the contents of that ActiveAdmin rb file.

For example, for this case PGError: ERROR: relation "users" does not exist, comment out the entire contents of app/admin/users.rb, then uncomment after you've done your migrations.

I was getting this error as well when running rspec:

 Failure/Error: it { expect(subject.priority_list).to eq [nil] * 9 }
ActiveRecord::StatementInvalid:
PG::UndefinedTable: ERROR:  relation "priorities" does not exist
LINE 5:              WHERE a.attrelid = '"priorities"'::regclass
...

It was resolved for me after I ran

rake db:test:prepare
rake db:test:load

In my case, I had to comment out 2 ActiveAdmin files. Here were my steps:

  1. Initial error/stacktrace (note we're using Solr on this project): ⇒ rkdbm java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) => Solr is already running rake aborted! PG::UndefinedTable: ERROR: relation "discussions" does not exist LINE 5: WHERE a.attrelid = '"discussions"'::regclass ^ : SELECT a.attname, format_type(a.atttypid, a.atttypmod), pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"discussions"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum /Users/matthewcampbell/Sites/code/stack-builders/AchieveX/app/admin/users.rb:25:in block in <top (required)>' /Users/matthewcampbell/Sites/code/stack-builders/AchieveX/app/admin/users.rb:1:in' /Users/matthewcampbell/Sites/code/stack-builders/AchieveX/config/routes.rb:3:in block in <top (required)>' /Users/matthewcampbell/Sites/code/stack-builders/AchieveX/config/routes.rb:1:in' /Users/matthewcampbell/Sites/code/stack-builders/AchieveX/config/environment.rb:5:in `' Tasks: TOP => db:migrate => environment (See full trace by running task with --trace)

I commented out the app/admin/discussions.rb file per Arcolye's answer above and tried to migrate my database again.

Same error.

I looked at the stacktrace a bit more closely, and noticed that in fact app/admin/users.rb:25 was throwing the exception - and sure enough, that file has a dependency on my discussions table (via executing Discussion.all).

Finally, commenting out the contents of users.rb allowed me to finally migrate my database successfully.

FYI: there's a discussion here in ActiveAdmin about whether that gem should load the database when required.

I was getting a similar error while trying to run tests using rspec.

I followed Малъ Скрылевъ's steps but still ended up short. The final step I needed to do was load my schema into my test database using:

RAILS_ENV=test rake db:schema:load

After that the problem went away and I could move on to the next bug. Hopefully that gives you some insight.

I had a similar error. The root of my error was that I had a reference to a Rails model in my factories.rb file. So it caused a load error issue. The fix was to wrap the reference in a block or {} so that it delays running it.

Here was the BROKEN code:

FactoryGirl.define do
factory :user do
guid User.new.send(:new_token)
end
end

And it was erroring because User was not defined when factories.rb was being loaded. I wrapped the User.new call in a block and it solved the issue:

Fixed code:

FactoryGirl.define do
factory :user do
guid { User.new.send(:new_token) }
end
end

Note: probably not best practice to need to call your model like this, but it was a solution to DRY up my code.

I had this problem after I deleted the users table. solutions was changing

change_table(:users)

to

create_table(:users)

So having the same problem just now. Remember to have only one model in each migration. That solved it for me.

I came across the answer here.

Remove the Admin folder and run rake again.

(I know this is old, but for future googlers)

Are you using devise? I know specifically omniauthable is a problem, but maybe others as well. It doesn't have to be devise though. Generically the solution is to comment out the offending model, class, whatever, and un-comment any sections the errors ask for.

For me, what was happening is that devise is reading the User model to see what you have as arguments for devise (the class method i.e. devise :database_authenticatable, :registerable #etc)

But, it will read the whole file and if this isn't a new project it might get tripped up by other class methods relying on other things (in my case it was the friendly_id gem, and then an alias_method

The answer was to comment out the User model except for the devise lines(s) * and rake db:schema:load should run fine.

  • otherwise I got this error:

    ArgumentError: Mapping omniauth_callbacks on a resource that is not omniauthable Please add devise :omniauthable to the User model

I had this problem and it turned out to be caused by Grape API. I noticed in the stack trace that the routes file was being read during the migration.

In routes.rb the Grape api is mounted

mount API::Base => '/'

And in the API were references to the missing model. So, thanks to this answer I put it in a block that detects whether its being run by the server or during the migration.

unless ( File.basename($0) == "rake" && ARGV.include?("db:migrate") )
mount API::Base => '/'
end

And it worked.

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

That issue for me was being caused by Factory Girl rails. I would recommend for those using it to rename the specs/factories folder to specs/temp and attempting

RAILS_ENV=your_environment bundle exec rake db:migrate --trace

If it passes, then you just found what was causing it. A quick dig through the Factory Girl Rails gem github repo helped me identify the issue.

The factories were failing because I was trying to instantiate a Model that didn't exist upon running! Code sample below:

FactoryGirl.define do
factory :billing_product, class: 'Billing::Product' do
name            Faker::Cat.name
product_type    'fuel'
active          true
payment_options [Billing::PaymentOption.new(term: 1, payment_term: 1)]
end
end

Encapsulating the Array in a block (adding {}) did the fix for me. Note that payment_options can take more than one payment option in the example...

payment_options {[Billing::PaymentOption.new(term: 1, payment_term: 1)]}

Refer to the Dynamic Attributes part of the Factory Girl Rails docs for more info.

Don't forget to rename your factories folder back!

I was having the following error and doing a lookup into all my application code for type_zones I was unable to find it. I also looked at the db and it was updated.

Turns out it was a file under fixtures /test/fixtures/type_zones.yml that was causing the trouble.

ERROR["test_should_get_new", UsersControllerTest, 0.47265757399145514]
test_should_get_new#UsersControllerTest (0.47s)
ActiveRecord::StatementInvalid:  ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "type_zones" does not exist
LINE 1: DELETE FROM "type_zones"
^
: DELETE FROM "type_zones"

::Migration[5.0] was missing in migrations. instead of throwing syntax error it throws

PG::UndefinedTable: ERROR: relation roles does not exists

after wasting hours I finally figured out that migration is missing ::Migration[5.0].

Erroneous Migration:

class CreateRoles < ActiveRecord # <---- Pay attention
def change
create_table :roles do |t|
t.string :name
t.integer :code, limit: 2
t.boolean :is_active, default: true


t.timestamps
end
end
end

Fixed and Correct Migration

class CreateRoles < ActiveRecord::Migration[5.0]
def change
create_table :roles do |t|
t.string :name
t.integer :code, limit: 2
t.boolean :is_active, default: true


t.timestamps
end
end
end

This could be a bug with rails and might help someone, instead of struggling and wondering.

For anyone who is still having this problem, in my case, it was my factory in FactoryGirl that was triggering this error.

I was trying to add reference via '.new' or '.create'.

I was catching the Error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "users" does not exist
LINE 8:                WHERE a.attrelid = '"users"'::regclass

It turned out to be a super easy fix. I had copied files over from an older version of the project and forgot to nest them inside of a "migrate" folder. When I did that it solved the problem for me.

I was facing the same problem and then I discovered the following solution.

Make sure You have entered all of the following credentials in the database.yml file and they are correct:

development:
adapter: postgresql
encoding: unicode
database: my_database
host: localhost
port: 5432
pool: 5
username: postgres
password: xyz


test:
adapter: postgresql
encoding: unicode
database: my_test_database
host: localhost
port: 5432
pool: 5
username: postgres
password: xyz

If you get this error while migrating, make sure your model name is plural

e,g.

add_column :images, :url, :string

it usually can happen when you use wrong type of association between models, check for dependency destroy and has_many associations, for example:

wrong way that can cause this trouble:

article.rb

 has_many :subcategories, through: :categories, dependent: :destroy

subcategory.rb

has_and_belongs_to_many :articles

right way:

article.rb

 has_many :subcategories, through: :categories, dependent: :destroy

subcategory.rb

declare association with categories here not articles (belongs_to / has_many_and_belongs_to)

Forgetting the migration file in your commit can cause this issue. When pushed on heroku for e.g. rails db:migrate will obviously not work. Be sure that the migration file defining the undefined table have been committed.

My case was also related to FactoryGirl/FactoryBot and I just had to change the definition. Replacing the constant by a string.

My env:

Rails 5.2.6
factory_bot 4.8.2

From this:

FactoryBot.define do
factory :user, class: Admin::User do
...
end
end

To this:

FactoryBot.define do
factory :user, class: 'Admin::User' do
...
end
end

Which is something recommended by Getting Started - Specifying the class explicitly.