I’m importing data from a legacy system and I need to keep primary keys of a given table intact. For example, this record might exist in the legacy countries
table:
id | alpha2 | name
––––––––––––––––––––
2 | SE | Sweden
Importing this record with the ID is simple enough with:
Country.new(id: 2, alpha2: "SE", name: "Sweden").save!
Now that record exists in the system. If I create a new record without specifying the ID:
Country.new(alpha2: "NO", name: "Norway").save!
…Then Norway also exists in the system, and is assigned an ID of 1
.
The problem arises when I try to create another model like this:
Country.new(alpha2: "DK", name: "Denmark").save!
Because a record already exists with an ID of 2
, I have a collision and sure enough AR/PG throws an exception:
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint
Is there a way to work around this problem? Can I ask AR to look for the next available ID? Should I try updating the ID sequence after a DB import so any new records are given an ID at least one higher than the highest-number ID found in the legacy DB?