Home > Software design >  How to avoid duplicate keys from seeding in Rails?
How to avoid duplicate keys from seeding in Rails?

Time:06-22

I'm running Rails 7.1 and Postgresql 14.

I have a Rails app that seeds the test db with some models with IDs 1 and 2. When I run my tests and my code tries creating a new model, I get an error:

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "model_pkey"
DETAIL:  Key (id)=(1) already exists.

However, when I run my tests additional times it (apparently) autoincrements the ID enough times where this isn't a problem. But right now the first 1 or 2 test runs always fail because of this, and this will break CI when we add it. Any ideas on how to solve this?

CodePudding user response:

Only assumption, but in initial state you have already some records in table, and sequence set to 1. Each insert (successfully or with error) increase sequence, and when sequence serve next number it is not in table, and from that point program starts to work.

CodePudding user response:

When you run rails db:seed, the table is exist column with id = 1, 2... after that, you create a new column, it is error. So, you should create a seed:

[
  {id: 1, email: "[email protected]", password: "password"},
  {id: 2, email: "[email protected]", password: "password"},
  {id: 3, email: "[email protected]", password: "password"},
].each do |attr|
  user = User.find_by(id: attr[:id])
  User.transaction do
    unless user
      user = User.new(attr)
      user.save
    else
      user.update_attributes attr
    end
  end
end
  • Related