Ruby-on-rails PG undefinedtable 错误关系用户不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19097558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:47:15  来源:igfitidea点击:

PG undefinedtable error relation users does not exist

ruby-on-railsdatabaseruby-on-rails-3oauth-2.0rake-task

提问by Naomi K

I saw this question up before, but only for rspec. I haven't created test yet because it's too advanced for me but one day soon i will! :P

我之前看到过这个问题,但仅适用于 rspec。我还没有创建测试,因为它对我来说太先进了,但很快有一天我会!:P

I get this error when I try to sign-up/login into my app. I used devise to create user and also omniauth2to sign-in with google.

当我尝试注册/登录我的应用程序时出现此错误。我使用devise创建用户并使用omn​​iauth2登录google

this is the error

这是错误

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

I tried rake db:migrate, but it already is created: in schema table users exist. Has anyone got this error before?

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

database.yml

数据库.yml

config=/opt/local/lib/postgresql84/bin/pg_config

配置=/opt/local/lib/postgresql84/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:

回答by Малъ Скрылевъ

At first, you shall detach all connections out of database. By default you use the developmentenvironment. 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

rake db:reset 任务将删除数据库并重新设置它。这在功能上等同于 rake db:drop db:setup。

这与运行所有迁移不同。它只会使用当前 schema.rb 文件的内容。如果迁移无法回滚, rake db:reset 可能无济于事。要了解有关转储架构的更多信息,请参阅架构转储和您部分。Rails 文档

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):

或简而言之(自 3.2 起):

rake db:migrate:reset db:seed

Since db:migrate:resetimplies drop, create and migrate the db. Because the default environment for rakeis development, in case if you see the exception in spec tests, you should re-create db for the testenvironment as follows:

由于db:migrate:reset意味着删除、创建和迁移数据库。因为默认环境rakedevelopment,如果你在 spec 测试中看到异常,你应该为测试环境重新创建 db如下:

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:seedtask action isn't required to be passed. Otherwise, you shall to prepare the database (this is deprecated in Rails 4):

在大多数情况下,测试数据库是在测试过程中播种的,因此db:seed不需要通过任务操作。否则,您应该准备数据库(这在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::NoEnvironmentInSchemaErrormay be risen, so just prepend the tasks with a database environment set task: db:environment:set:

在较新版本的 Rails 上,错误ActiveRecord::NoEnvironmentInSchemaError可能会出现,因此只需在任务前面加上数据库环境集任务:db:environment:set

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

回答by supritshah1289

I encountered this error, and upon my research, found out that one of the reasons for PG undefinedtable error relation users does not existerror is:

我遇到了这个错误,经过我的研究,发现PG undefinedtable错误关系用户不存在错误的原因之一是:

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.

此错误是迁移错误。您可能创建了具有某些数据库属性的新模型。创建模型后,您必须将属性迁移到 Rails 应用程序架构。

If you are using local machine, for development, you can use command

如果您使用的是本地机器,对于开发,您可以使用命令

rake db:migrate

If you're using heroku

如果您使用的是heroku

heroku run rake db:migrate

回答by Serge Seletskyy

Your test database is not ready for rspec.

您的测试数据库还没有为 rspec 做好准备。

Prepare your test database for rspec to fix this error

为 rspec 准备测试数据库以修复此错误

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

如果 rake 任务被中止,并出现“PG::Error: ERROR: database "[your_db_test]" is being accessing by other users' 之类的消息,请执行此操作

RAILS_ENV=test rake db:migrate

回答by ehc

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.

我有一个类似的错误。我的错误根源在于我在 factory.rb 文件中引用了 Rails 模型。所以它导致了加载错误问题。解决方法是将引用包装在一个块中,或者{}延迟运行它。

Here was the BROKEN code:

这是破碎的代码:

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

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

它是错误的,因为User在加载factory.rb时没有定义。我将User.new调用包装在一个块中,它解决了这个问题:

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.

注意:可能不是需要像这样调用模型的最佳实践,但它是干掉我的代码的解决方案。

回答by Arcolye

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

这通常是由 ActiveAdmin 中的错误引起的。以下是解决该错误的方法:

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

如果您正在使用 ActiveAdmin,无论 PG 说哪个表不存在,请注释掉该 ActiveAdmin rb 文件的内容。

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.

例如,对于这种情况PGError: ERROR: relation "users" does not exist,将 的全部内容app/admin/users.rb注释掉,然后在完成迁移后取消注释。

回答by cedricdlb

I was getting this error as well when running rspec:

运行 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

回答by Igi Manaloto

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

对我来说,那个问题是由 Factory Girl 导轨引起的。我会建议那些使用它重命名 specs/factories 文件夹的人为 specs/temp 并尝试

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

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.

如果它通过了,那么您就找到了导致它的原因。快速浏览 Factory Girl Rails gem github repo 帮助我确定了问题。

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...

将 Array 封装在一个块中(添加 {})为我做了修复。请注意,在示例中,payment_options 可以采用多个付款选项...

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

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

有关更多信息,请参阅Factory Girl Rails 文档动态属性部分

Don't forget to rename your factories folder back!

不要忘记重命名您的工厂文件夹!

回答by Muhammad Zubair

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:

确保您在 database.yml 文件中输入了以下所有凭据并且它们是正确的:

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 

回答by Kaleem Ullah

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

::Migration[5.0]在迁移中丢失。它抛出的不是抛出语法错误

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

PG::UndefinedTable:错误:关系角色不存在

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

在浪费了几个小时之后,我终于发现迁移丢失了::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.

这可能是 rails 的一个错误,可能会帮助某人,而不是挣扎和疑惑。

回答by KnuturO

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

删除用户表后我遇到了这个问题。解决方案正在改变

change_table(:users)

to

create_table(:users)