Skip to content

Instantly share code, notes, and snippets.

@dougalcorn
Created October 30, 2018 15:37
Show Gist options
  • Save dougalcorn/12d3906321589e46aa12f556428acda0 to your computer and use it in GitHub Desktop.
Save dougalcorn/12d3906321589e46aa12f556428acda0 to your computer and use it in GitHub Desktop.
Resetting Primary Key Sequence in Rails

I exported a table worth of data from one postgres instance as CSV and then directly imported into another postgres instance bypassing rails using the \copy command like so:

\copy my_table to ‘my_table.csv’ csv;

and

\copy my_table from ‘my_table.csv’ with (format csv);

Then I noticed that Rails was unable to create new records for that table:

MyModel.create(name: “Foo”)
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint “my_models_pkey"

I could see quite clearly it was trying to insert with an id of “1”. The solution is to reset the primary key sequence like this:

ActiveRecord::Base.connection.reset_pk_sequence!(‘my_table’)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment