0

I am using rails 7 and postgres 14.5 and active record now seems out of sync with postgres.

I saved a user and I got ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "users_pkey" DETAIL: Key (id)=(3) already exists. ):

From PostgreSQL: Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_pkey", I ran SELECT setval(pg_get_serial_sequence('users', 'id'), coalesce(max(id)+1, 1), false) FROM users; which seemed to fix that initial issue and allowed me to save the user.

Then I destroyed the user and tried to save the user again and now I'm getting ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email" DETAIL: Key (email)=(test@test.com) already exists. ):

This is telling me that my active record is out of sync with my postgres.

Any ideas on how I can fix this out of sync issue or at least fix the index issue now?

monty_lennie
  • 2,871
  • 2
  • 29
  • 49
  • Those errors are being returned by the database meaning the database is returning error code 23505 resulting in the error message you are seeing. [PG::UniqueViolation](https://github.com/ged/ruby-pg/blob/master/ext/errorcodes.def#L391). You can reset the primary key sequence for the table via `ActiveRecord::Base.connection.reset_pk_sequence!('table_name')` but the second error means that email already exists and you should look at the data in the database. – engineersmnky Jan 06 '23 at 20:42
  • Could you provide more context as to when you are getting these errors? Are they in a testing suite where maybe you have set things up incorrectly and you are incidentally creating your own collisions, perhaps? – engineersmnky Jan 06 '23 at 20:45

0 Answers0