Me
Blog about Ruby, Rails, and more!

Fixing PG::UniqueViolation: ERROR: duplicate key value violates unique constraint

2017-08-13

If you are seeing ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint...), it means that active record is attempting to create a record with a primary key that is already in use.

Why is this happening? Postgres keeps track of your current sequence value, which is waht Active Record looks at when it attempts to asssign an id to a new record. In this case, the sequence has been changed without Active Records knowledge.

To fix the issue, we have to tell Active Record to go back and look at the sequence of the table:

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

Now Active Record should have the correct sequence value, and should be able to assign new id's properly.