0

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?

Jezen Thomas
  • 13,619
  • 6
  • 53
  • 91
  • 2
    As you've suggested, you could start the ID count for new records at a point that is beyond your legacy IDs. See `reset_pk_sequence` as suggested in [this answer](http://stackoverflow.com/a/15108735/2622934). – cschroed Oct 25 '14 at 14:15
  • Ah, that’s very helpful. Thanks. My question is pretty much the same as the one you linked to, so I’ll vote to close my question. – Jezen Thomas Oct 25 '14 at 14:20

0 Answers0