I am Rails 5.1 with Postgresql 9.6.9 on Heroku free tier.
I recently was using a rake task with csv files to try to create a couple of batches or records. I then wanted to test the front end use and just verify my forms were working like they do in development.
However, when I went to add a new Record with the form I kept getting a 500 error. When I check my Heroku logs, I got this error.
ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "games_pkey"
It would list the id it was trying to use, which would be a lower id that was used when I imported records via the rake task and csv file.
I confirmed this truly was the issue by continuously attempting to use my form to create the record, which finally went through after about 20 attempts and it got to the correct next id.
I am not sure if this is an error caused by Postgres or Rails. It clearly was started when I started using the rake task and csv file. The csv file does have an attribute for ID which was being used for an easy check to either update or create a new file, but perhaps this was my cause.
Any advice on how to prevent this error would be great, as I have also uploaded other csv files for other models in even bigger batches. I would like to continue to do so, but only if I can avoid this error, so that I can add on one or two by the simple form I have when possible.
Thank you for your help.
Here is the rask task code that maybe is causing an issue:
CSV.foreach(filename, {col_sep: ";", headers: true}) do |row|
game_hash = row.to_h
game = Game.find_by(id: game_hash["id"])
if(!game)
game = Game.create(game_hash)
else
game.update(game_hash)
end
end