Seeds.rb sets primary key value, results in duplicate key error

heroku, postgresql, ruby-on-rails

Solution

The :id column is an auto-increment column. As such, you don't have control over what value it uses -- it just always uses the next id available in its internal counter. If this were me I'd find some other way to identify those few records than by :id. For example, maybe you can refer to the records by a :name or some other special attribute? (Don't forget to index the attribute you're finding by if you do go this route!)

Then, I'd use the seed_fu gem to perform idempotent seeding, as you seem to be wanting. With idempotent seeding, if a record exists already then it will be updated (if there are any updates to be performed; if not then it's a no-op). This way you don't have exceptions and you can always add new or update existing records.

Problem

In my Rails 4 app, which I am using on Heroku for production, I have set up a seeds.rb file for the initial set of data. As it is critical that a few records have specific primary ids, say in the 'activities' table, I have set those. All goes well. UNTIL. Until I need to add a new activity to the activities table. Adding a new record will fail as many times as there are records in that table, while the sequencer catches up. (e.g. if I have three records, new record creation fails three times, succeeds on the fourth). QUESTION: How can I get the primary ID counter on the Heroku postgres database to start after the highest primary id set in my seeds.rb file? If you don't know, what terms should I be googling? Ideally, this solution would be automatic, and not something I have to open psql for each time I seed the database. Thanks in advance.

Original source

Related problems