Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails postgreSQL duplicate key

I have a Rails app that uses postgreSQL.

I recently did a backup of production and restored it to development.

When I try to add a Payment record in development, I get:

ERROR:  duplicate key value violates unique constraint "payments_pkey"
DETAIL:  Key (id)=(1) already exists.

Yet, there is only one record in the table with id=1 and the payments_id_seq has Current value = 1.

So, whey isn't Rails trying to add id=2 ??

Thanks for the help!

PS - is there a script or command in pgadmin to force the id_seq to be correct?

like image 847
Reddirt Avatar asked Sep 23 '26 09:09

Reddirt


1 Answers

If you receive a PostgreSQL unique key violation error message ("duplicate key value violates unique constraint..."), probably your primary key index is out of sync, e.g. after populating the database.

Use

ActiveRecord::Base.connection.reset_pk_sequence!('[table_name]')

to fix the sequence for the users table.

like image 79
a learner has no name Avatar answered Sep 24 '26 23:09

a learner has no name