How to change column default in rails?

less than 1 minute read

Syntax

change_column_default(table_name, column_name, default_or_changes)

Example

change_column_default(:users, :state, 'active')

Rails Command:

$ rails generate migration change_column_default_for_state
      invoke  active_record
      create    db/migrate/20230906142034_change_column_default_for_state.rb

The above command will generate a migration

class ChangeColumnDefaultForState < ActiveRecord::Migration[7.1]
  def change
  end
end

We need to modify it to:

class ChangeColumnDefaultForState < ActiveRecord::Migration[7.1]
  def change
    change_column_default(:users, :state, from: nil, to: 'active')
  end
end

This migration will update the schema to set the default value of the status column to “active” for all existing records.

It is recommended to pass :from and :to as it helps while reverting the migration

NOTE:

setting default to nil drops the default.

References