why PG::UniqueViolation: ERROR: duplicate key value violates unique constraint?

To fix the issue, we have to tell ActiveRecord to look at the sequence of the table:

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

Now ActiveRecord should have the correct sequence value, and should be able to assign new id’s properly.

To resolve error

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint “moderations_reportable” DETAIL: Key (reportable_type, reportable_id)=(Post, 25) already exists. : INSERT INTO “moderations” (“blog_id”, “reportable_type”, “reportable_id”, “created_at”, “updated_at”, “blog_type”) VALUES ($1, $2, $3, $4, $5, $6) RETURNING “id”

As error occurred on ‘moderations’ table.

Run the following from rails console fix

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

Thank you

Leave a Comment