Ruby-on-rails 在 ID 存在时获取“表的未知主键”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18056162/
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:28:39  来源:igfitidea点击:

Getting "Unknown primary key for table" while the ID is there

ruby-on-railspostgresqlherokurails-activerecordheroku-postgres

提问by hakunin

I've been debugging this strange problem of Rails giving me "Unknown primary key for table...", even when the table's ID is there.

我一直在调试 Rails 的这个奇怪问题,它给我“表的主键未知...”,即使表的 ID 存在。

I've copied the database from one heroku app to another, on the original databse there is no problem and the new one gives me a db error.

我已将数据库从一个 heroku 应用程序复制到另一个应用程序,在原始数据库上没有问题,而新数据库给了我一个 db 错误。

This is the error:

这是错误:

ProductsController# (ActionView::Template::Error) "Unknown primary key for table collections in model Collection."

/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:366:in `primary_key'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:480:in `association_primary_key'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:58:in `block in add_constraints'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `each_with_index'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `add_constraints'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:31:in `scope'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:98:in `association_scope'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:87:in `scoped'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:573:in `first_or_last'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:105:in `last'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_proxy.rb:46:in `last'
/app/app/helpers/likes_helper.rb:62:in `significant_liker'

The line that causes it:

导致它的行:

product.collections.last.try :user

and the table:

和表:

d8apjspa441pad=> \d collections
                                     Table "public.collections"
     Column     |          Type          |                        Modifiers                         
----------------+------------------------+----------------------------------------------------------
 id             | integer                | not null default nextval('collections_id_seq'::regclass)
 name           | character varying(255) | 
 user_id        | integer                | 
 permalink      | character varying(255) | 
 category_id    | integer                | 
 products_count | integer                | 
 is_featured    | boolean                | 
Indexes:
    "index_lists_on_user_id_and_permalink" UNIQUE, btree (user_id, permalink)

Any idea why this might happen?

知道为什么会发生这种情况吗?

Thanks!

谢谢!

回答by Debadatt

Seems primary key is missing for the table collections.

表集合似乎缺少主键。

Prior to Rails 3.2, set the primary key in model like

在 Rails 3.2 之前,在模型中设置主键,如

class Collection < ActiveRecord::Base
  set_primary_key "my_existing_column"
end

In Rails 3.2+ and Rails 4, set the primary key in model like

在 Rails 3.2+ 和 Rails 4 中,在模型中设置主键,如

class Collection < ActiveRecord::Base
  self.primary_key = "my_existing_column"
end

OR

或者

We can alter the table and set the primary key for id like

我们可以更改表并为 id 设置主键,例如

Create a migration file to set the primary key

创建迁移文件来设置主键

class AddPrimaryKeyToCollections < ActiveRecord::Migration
 def change
   execute "ALTER TABLE collections ADD PRIMARY KEY (id);"
 end
end

回答by elc

I was having a similar problem and this was the only page I could find. So just in case it will be of help to anyone else...

我遇到了类似的问题,这是我唯一能找到的页面。所以以防万一它对其他人有帮助......

I started suddenly getting missing primary key messages on a couple tables. I'm guessing, but not sure, that this started happening after pushing data (pg_dump local, heroku pg:restore)

我突然开始在几个表上丢失主键消息。我猜测,但不确定,这是在推送数据后开始发生的(pg_dump local,heroku pg:restore

The primary keys in question were both on tables that had been renamed so that the pkey name did not match the table name--but on the other hand lots of other renamed tables were in the same boat and did not have problems.

有问题的主键都在已重命名的表上,因此 pkey 名称与表名称不匹配——但另一方面,许多其他重命名的表在同一条船上并且没有问题。

Anyway, at one point in my flailing around I tried uploading another dump file and I noticed some complaints on the offending indices. First it would try to delete them and complain that it couldn't because they did not exist. Later it would try to create them and complain that it couldn't because they already existed.

无论如何,在我四处游荡的某个时刻,我尝试上传另一个转储文件,但我注意到一些对违规索引的抱怨。首先它会尝试删除它们并抱怨它不能,因为它们不存在。后来它会尝试创建它们并抱怨它不能,因为它们已经存在。

Very annoying considering that pkey info doesn't show up in schema.rband is supposed to 'just work', right?

考虑到 pkey 信息没有出现schema.rb并且应该“正常工作”,这很烦人,对吧?

Anyway, what worked for me (and thus the reason I'm posting) is to do a heroku pg:resetand then load the dump again. Side note, I got 'internal server error' the first two times I tried heroku pg:reset. But later I tried again and it worked.

无论如何,对我有用的(也是我发帖的原因)是执行 aheroku pg:reset然后再次加载转储。旁注,我尝试的前两次出现“内部服务器错误” heroku pg:reset。但后来我又试了一次,它奏效了。

回答by Jake Worth

I was recently encountered this error: "Unknown primary key for table", and like the question asker, it appeared after copying a database to a Heroku app. TL;DR: try restarting the app.

我最近遇到了这个错误:“表的主键未知”,就像提问者一样,它是在将数据库复制到 Heroku 应用程序后出现的。TL;DR:尝试重新启动应用程序。

In my case, the source database had no error, so I was confident the table and primary key were fine.

就我而言,源数据库没有错误,所以我确信表和主键没问题。

I tried a few suggestions on this page, including starting from scratch with a heroku pg:reset, new pg_dumpof the old database, and pgbackups:restoreinto the new database, then running migrations and seeding... nothing worked.

我尝试了一些建议,这个页面上,包括从头开始了heroku pg:reset,新的pg_dump旧的数据库,并pgbackups:restore进入新的数据库,然后运行的迁移和播种......毫无效果。

What finally solved my problem: restarting the app. The new app had many database migrations, and running heroku restartreloaded the schema and picked up the schema changes. This page from Heroku's documentation explains:

最终解决了我的问题的是:重新启动应用程序。新应用程序有许多数据库迁移,运行时会heroku restart重新加载架构并获取架构更改。Heroku 文档中的这个页面解释了:

Running Rake Commands

运行 Rake 命令

After running a migration you'll want to restart your app with heroku restart to reload the schema and pickup any schema changes.

运行迁移后,您需要使用 heroku restart 重新启动应用程序以重新加载架构并获取任何架构更改。

回答by Michiel de Mare

What helped for me (happened on heroku after a db restore) is reindexing the primary key index:

对我有帮助的(在数据库恢复后发生在 heroku 上)是重新索引主键索引:

reindex index $primary_key_index_name

reindex index $primary_key_index_name

回答by rubyonrails3

I was restoring database dump from heroku to my local system and was getting this error..

我正在将数据库转储从 heroku 恢复到我的本地系统并收到此错误..

ActiveRecord::UnknownPrimaryKey: ActiveRecord::UnknownPrimaryKey

I was restoring on existing database, so I dropped the database, created new database and then restore the dump and it worked for me

我正在恢复现有数据库,所以我删除了数据库,创建了新数据库,然后恢复了转储,它对我有用

回答by loybert

restarting the heroku server worked for me. Maybe it was the spring-preloader which was recognizing the empty db-schema, during the db-restorement

重新启动 heroku 服务器对我有用。也许是弹簧预加载器在数据库恢复期间识别了空的数据库模式

回答by aldrien.h

I encountered this error doing tests in RSPEC.

我在 RSPEC 中进行测试时遇到了这个错误。

In my case, i solved it by adding/setting primary_key in my Rails model

就我而言,我通过在 Rails 模型中添加/设置 primary_key 来解决它

class Tablename < ApplicationRecord
   self.primary_key ="id" if Rails.env.test? #optional condition
   ......
end

回答by Undistraction

If you're trying to troubleshoot this issue make sure you check your logs carefully. I noticed an earlier error related to a js asset that wasn't being precompiled. This got lost in the stack of rendering messages.

如果您正在尝试解决此问题,请确保仔细检查您的日志。我注意到一个与未预编译的 js 资产相关的较早错误。这在渲染消息堆栈中丢失了。

Once I fixed the asset precompilation issue, the 'Unknown primary key for table' error was no longer thrown.

一旦我修复了资产预编译问题,就不再抛出“表的未知主键”错误。

This was 100% definitely the only thing I changed.

这绝对是我唯一改变的 100%。

回答by Jason Swett

I was having this problem and the issue turned out to be that my table somehow actually didn't have a primary key index. The solution was to create a migration that added a primary key:

我遇到了这个问题,结果是我的表不知何故实际上没有主键索引。解决方案是创建一个添加主键的迁移:

execute "ALTER TABLE appointment_reminder_text ADD PRIMARY KEY (id)"

回答by Nathan Bertram

Thanks changing the index above worked for me. Just another quick note about how this error will manifest itself if there's a more complex relation involved:

感谢更改上面的索引对我有用。关于如果涉及更复杂的关系,此错误将如何表现出来的另一个快速说明:

ActiveRecord::StatementInvalid - PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: ...CT "users".* FROM "users"  WHERE "benefits"."" IN ('1'...