Rails auto-assigning id that already exists Rails auto-assigning id that already exists postgresql postgresql

Rails auto-assigning id that already exists


I did this which solved the issue for me.

ActiveRecord::Base.connection.tables.each do |t|  ActiveRecord::Base.connection.reset_pk_sequence!(t)end

I found the reset_pk_sequence! from this thread. http://www.ruby-forum.com/topic/64428


Rails is probably using the built-in PostgreSQL sequence. The idea of a sequence is that it is only used once.

The simplest solution is to set the sequence for your company.id column to the highest value in the table with a query like this:

SELECT setval('company_id_seq', (SELECT max(id) FROM company));

I am guessing at your sequence name "company_id_seq", table name "company", and column name "id" ... please replace them with the correct ones. You can get the sequence name with SELECT pg_get_serial_sequence('tablename', 'columname'); or look at the table definition with \d tablename.

An alternate solution is to override the save() method in your company class to manually set the company id for new rows before saving.


Based on @Apie answer.

You can make a task and run when you need with:

rake database:correction_seq_id

You create tasks like this:

rails g task database correction_seq_id

And in the file generated (lib/tasks/database.rake) put:

namespace :database do    desc "Correction of sequences id"    task correction_seq_id: :environment do        ActiveRecord::Base.connection.tables.each do |t|            ActiveRecord::Base.connection.reset_pk_sequence!(t)        end    endend