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

13

46

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

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.

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!

Scheider answered 5/8, 2013 at 10:39 Comment(2)
Seems primary key index is missing from collections.Iver
Can you share for my & other's benefit how to establish it in an answer?Scheider
I
47

Seems primary key is missing for the table collections.

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

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

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

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
Iver answered 5/8, 2013 at 12:31 Comment(4)
Hmm, I thought you mean to setup primary key in DB, thats what I did and although it complained about the key being already set, the app started working. Can you explain why I'd use set_primary_key even if the ID is just the default id? Might come handy.Scheider
Porbably your collections table misses one primary key index in db. Each table should have a primary key. As the table here looses the primary key we need to set it up. But default id could not set up as a primary key.. so it raises excepition.Iver
So basicaly, I had two options - explicitly tell Rails, or set up the DB attribute correctly, right? If you add the PSQL to setup the attribute I'll accept your answer.Scheider
Rails 4 users: self.primary_key = 'my_existing_column' insteadDensmore
T
18

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)

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.

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.rb and is supposed to 'just work', right?

Anyway, what worked for me (and thus the reason I'm posting) is to do a heroku pg:reset and 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.

Traylor answered 14/8, 2013 at 21:47 Comment(0)
C
17

TL;DR: try restarting the app.

heroku restart

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

The copied database had no errors, 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_dump of the old database, and pgbackups:restore into the new database, then running migrations and seeding... nothing worked.

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

Running Rake Commands

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

Cruce answered 16/7, 2014 at 4:11 Comment(3)
Simply restarting also worked for me with this error after a capistrano deploy.Greenleaf
heroku pg:reset then reimporting the DB worked for me. I had manually created an index on the production DB and it wasn't getting copied over correctly to the staging DBJehanna
heroku restart solved my issue tooTarantula
B
3

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

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

Blida answered 28/2, 2017 at 17:27 Comment(1)
Also re-loading the schema then restoring the dump works as wellAnisomerous
M
2

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

reindex index $primary_key_index_name

Metabolism answered 15/4, 2015 at 18:48 Comment(4)
Where do you type this in?Gangboard
In the psql console.Metabolism
I was getting the error in production (on Heroku) after a push. Not sure I have access to the db console. Pushing again to Heroku seemed to fix it. Thanks for pointing me in the right direction.Gangboard
Reindexing solved my issue too (my app is not hosted on Heroku though). The main point here is don't forget to restart your application.Psychosomatics
K
2

The same thing happens to me also while importing the data dump from heroku to local. I have the Rails 5.1.6 for the application. After adding self.primary_key = "id" to all of the models which is showing issue, everything works fine for me.

Kuhlmann answered 7/6, 2020 at 19:48 Comment(0)
F
1

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)"
Fane answered 10/8, 2015 at 13:50 Comment(1)
This happened to me after merging several identical DBs into one for a multi-tenant setup. I was following some SQL guides that I didn't really deeply understand. I may have missed re-applying the primary key on that table or it was just munged in the restore process. Ran the code above and everything is good!Narrow
P
0

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.

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.

Pharisaism answered 7/3, 2014 at 21:29 Comment(0)
C
0

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'...
Clovis answered 28/4, 2016 at 6:40 Comment(0)
A
0

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

Awhile answered 24/9, 2018 at 10:8 Comment(0)
P
0

I encountered this error doing tests in RSPEC.

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

class Tablename < ApplicationRecord
   self.primary_key ="id" if Rails.env.test? #optional condition
   ......
end
Pellet answered 29/4, 2020 at 2:22 Comment(0)
A
0

You should reload the schema on the target app. Then load the database.

Anisomerous answered 4/8, 2020 at 7:37 Comment(0)
M
0

When I hit this recently, the root cause was a copy/paste error in structure.sql that led to a duplicate PK constraint getting defined. Confusingly, the duplicate key was unrelated to the table mentioned in the error, which still had its PK defined properly in my application DB. However, I was hitting this while running RSpec, so the test DB setup was failing silently upstream on the unrelated model, and then I guess the index mentioned in the error was never getting created for the model under test.

I was able to track it down by running bundle exec rake db:test:load which raised the actual error the test setup was failing on: ERROR: multiple primary keys for table "foo" are not allowed. Once I saw that, I was able to track down the duplicate constraint in structure.sql, remove it, and load/prepare without error, leaving RSpec once again in a working state.

Midbrain answered 28/3, 2023 at 19:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.