How can I rename a database column in a Ruby on Rails migration?

How can I rename a database column in a Ruby on Rails migration?

The easiest way to rename a database column in a Ruby on Rails migration is to use the rename_column method:

class RenameColumnInTable < ActiveRecord::Migration[5.2]
  def change
    rename_column :table_name, :old_column_name, :new_column_name
  end
end

If you need to rename multiple columns in a single migration, you can use the rename_columns method:

class RenameColumnsInTable < ActiveRecord::Migration[5.2]
  def change
    rename_columns :table_name, {
      :old_column_name_1 => :new_column_name_1,
      :old_column_name_2 => :new_column_name_2
    }
  end
end

If you need to rename a column and also change its data type, you can use the change_column method:

class ChangeColumnInTable < ActiveRecord::Migration[5.2]
  def change
    change_column :table_name, :column_name, :new_data_type
  end
end

If you need to rename a column and also change its data type and other options, you can use the change_column_null method:

class ChangeColumnInTable < ActiveRecord::Migration[5.2]
  def change
    change_column_null :table_name, :column_name, false, 0
  end
end

This will set the column to not allow NULL values and set the default value to 0.