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!
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
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.
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.
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
What helped for me (happened on heroku after a db restore) is reindexing the primary key index:
reindex index $primary_key_index_name
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)"
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.
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.
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'...
restarting the heroku server worked for me. Maybe it was the spring-preloader which was recognizing the empty db-schema, during the db-restorement
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
You should reload the schema on the target app. Then load the database.
Related
After migrating from RDS Postgresql to RDS Aurora PostgreSQL, I am having an issue to where new inserts are trying to start from key ID 2 instead of the last record.
In my rails app, here's what I'm seeing when I try to create a new record:
ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "global_options_pkey"
DETAIL: Key (id)=(3) already exists.
):
app/controllers/schedules_controller.rb:45:in `create'
Not sure why this would be the case. To set up Aurora PSQL in Rails, I followed this tutorial: https://guides.rubyonrails.org/active_record_multiple_databases.html. It seems like everything is working fine (auto switching between reader/writer instances, etc.).
With the migration, I specifically used the AWS Schema Conversion Tool (SCT), followed by a migration with the Database Migration Service.
Is this error caused by something that was done incorrectly in the migration process or do I need to some post-migration processes to have this fixed?
Definitely a case of when you migrated old data, but not with INSERT and your sequences are still on the initial values.
Use sequence manipulation functions to check what is the current value with lastval(), and set it to max(id) with setval()
You can try
ActiveRecord::Base.connection.tables.each do |table_name|
ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
end
After upgrading to rails 5.2 and running rake db:migrate I get the error below
ActiveRecord::NotNullViolation: Mysql2::Error: Field 'key' doesn't have a default value: INSERT INTO 'ar_internal_metadata'
I understand this is a new thing in rails 5 and above to prevent potential data loss in production. I can not find anywhere in the schema or migrations where this table is generated. It creates the key column with no default value and it can not be changed since it's a primary key. Any help would be greatly appreciated.
After some more research, I discovered that the values in the auto-generated ar_internal_metadata table only get set if you have an active migration while running rake db:migrate. The workaround is to set the values manually in the table so:
key -> environment and value -> production
hope this helps someone else.
I am trying to deploy to Heroku for the first time. During database migration I get error:
PG::UndefinedTable: ERROR: table "new_shops" does not exist
: DROP TABLE "new_shops"/app/vendor/bundle/ruby/2.1.0/gems/activerecord-new4.1.6/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:
in `async_exec'
new_shops is a table I thought I deleted with everything related to it (I followed instructions I've found here, although don't remember exactly what I did), but obviously I didn't.
Table itself is dropped, but something else is there. I am a newbie, so I have no idea what to do now or where to look.
What is the best way to destroy everything related to this table?
The table probably doesn't exist. You can check by running:
heroku pg:psql
\d new_shops
If it doesn't exist you should comment or remove the migration that is trying to drop the table.
I'm trying to update my heroku database. The problem: I created an old model & table that we no longer need. That table had previously been migrated to a production server (along with other changes). I did a destroy of the model using:
rails destroy model ReallyLongModelName
That also deleted the migration that created the table.
Later, I created a migration to drop that table.
class Drop_ReallyLongTableName < ActiveRecord::Migration
def change
drop_table :really_long_table_name
end
end
I'm now getting a couple of errors.
First error:
When trying to migrate the database to the production version of the application, I get this error.
Input string is longer than NAMEDATALEN-1 (63)
I'm not sure how to go back and edit the name to avoid the long name, so that it clears
Second error:
When trying to rollback the Drop_ReallyLongTableName migration, its aborts the rake because
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: no such table: really_long_table_name
Does anyone have any ideas on how to solve this? Thanks!
Have you tried running this from your Terminal/console:
heroku run console
ActiveRecord::Migration.drop_table(:table_name)
The migration is the way to go but this might be worth a try to see if the table even exists any more (since your second error message seems to indicate that it is no longer there).
Also, and for what it's worth, you can add conditional logic to your DB migrations should you need to in the future
def change
drop_table :table_name if self.table_exists?("table_name")
end
I am getting an error when I try to migrate my db. I don't entirely remember how I got here, but I believe I:
created new branch, scaffolded 'Requests', db:migrated, switched back to master, and merged branch
created another branch, did some stuff, db:migrated, and everything was working fine.
pulled from heroku postgres database so i could test out if things worked with actual data. then tried db migrating, but gave me this error:
rake db:migrate
== CreateRequests: migrating =================================================
-- create_table(:requests)
NOTICE: CREATE TABLE will create implicit sequence "requests_id_seq1" for serial column "requests.id"
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: relation "requests" already exists
: CREATE TABLE "requests" ("id" serial primary key, "title" character varying(255), "content" text, "category" character varying(255), "status" character varying(255), "requested_track_id" integer, "created_at" timestamp, "updated_at" timestamp)
Any ideas?
I'm not sure exactly what pull strategy you used, but if we make two reasonable assumptions about your pull strategy:
it doesn't drop the database but just overwrites tables, since this requires less permissions.
it is operating in a sort of 'archive mode', meaning it doesn't drop tables on the destination just because they don't exist on the source. Think rsync; you have to specify --delete to get what might be your expected behavior with that utility.
If your steps are correct, then what happened is you overwrote the schema_migrations table, so Rails thinks you haven't added the table yet, but neither did your heroku pull drop the table because of #2 above.
Don't create another migration!!! This will fail on everyone elses' computer except yours, but will only run on yours once.
Instead, run rails dbconsole and execute something like DROP TABLE 'requests' (I forget the postgres syntax, might not be exactly that). Then you can run your migrations.
There is another way to avoid dropping a table with data in it.
What I do in those cases is to check which migration is failing.
Suppose you have a file db/migrate/20130908214222_create_requests.rb, and for some reason, ActiveRecord failed in the past when stored this migration in its "tracking system".
To be sure that this is the case, just find, in the schema_migrations table, a row containing a number like this example: 20130908214222
If that row does not exist, you just have to insert a new one:
INSERT INTO schema_migrations(
version
) VALUES (
20130908214222
);
Next time you run rake db:migrate, ActiveRecord will omit this step, and will continue migrating to end without complications.