In Rails 5, how to drop the default value of primary key i.e. 'id' column and make it auto_increment again?

721 views Asked by At

In my rails application, there is a table with 'id' column default value set to 0. I want to drop this default value and make this column auto-increment again. I have tried

change_column_default(:table_name, :id, nil)

but it doesn't seem to work on primary key such as 'id'

2

There are 2 answers

3
DenicioCode On

Try to use

change_column :tabel_name, :column_name, :string, :default => nil
0
Taras On

That's work for me:

class MigrationName < ActiveRecord::Migration[6.0]
  def up
    max_id = TableName.maximum(:id) || 0
    execute "CREATE SEQUENCE IF NOT EXISTS \"table_name_id_seq\" START #{max_id + 1}"
    change_column_default :table_name, :id, -> { "nextval('table_name_id_seq'::regclass)" }
  end

  def down
    change_column_default :table_name, :id, nil
    execute 'DROP SEQUENCE "table_name_id_seq"'
  end
end