You're using sequential integer id's for your table according to the migration. This works well enough if you allow the database to assign id's for you. Every time a new record comes in, database takes the next number on the list and assigns it to that record (simplifying here).
Lets assume the database id sequence is currently at 3
and the records you imported have ids 4
, 37
and 143025
. Inserting a new record to the database, database says id is 3
, all good, sequence is now at 4
. Inserting another one, database says id is 4
. Trying to insert it, but there already is a 4
in the database.
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "table_pkey"
A few possible solutions:
- After importing, change the database id sequence to something bigger than the largest id you imported. (hacky, but works) Postgres manually alter sequence
- Import the items without hardcoding their id-s. (complicated)
- Change your database to use uuid-s instead of integer id-s (architectural change, difficult if the app is live, best solution if you're still in development)
- Use a proper database backup system rather than building your own. pg_dump
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…