DEV Community

Cover image for [Fix] Rails Auto Increment ID Postgres Error
Prabin Poudel for Truemark Technology

Posted on

1

[Fix] Rails Auto Increment ID Postgres Error

Error

ActiveRecord::RecordNotUnique Exception: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "users_pkey"
DETAIL: Key (id)=(43957) already exists.

Detail

You normally run into this error when you restore database from another source, for e.g. production or staging server.

This happens because of database sequence for Postgres that is stored in local machine is not the same as what comes from restored database and same id can be assigned twice when auto incrementing by Rails application.

Solution

We can reset the sequence of the table that is stored in the local machine by Postgres to fix this issue.

  1. Go to rails console

    rails c

  2. Reset the Postgres sequence for the table

    You can reset the Postgres sequence with the following command:

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

    E.g. Assuming the table name is users, you can do the following:

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

Conclusion

After resetting the sequence of table stored by Postgres, new records will be created without any issues.

Thanks for reading. Happy Coding!

References

Image Credits

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay