5

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'

mahemoff
  • 44,526
  • 36
  • 160
  • 222
Mohsin Sethi
  • 803
  • 4
  • 16

2 Answers2

0

Try to use

change_column :tabel_name, :column_name, :string, :default => nil
DenicioCode
  • 8,668
  • 4
  • 18
  • 33
0

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
Taras
  • 118
  • 8