Ruby on Rails ActiveRecord Migrations Change an existing column’s type

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To modify an existing column in Rails with a migration, run the following command:

rails g migration change_column_in_table

This will create a new migration file in db/migration directory (if it doesn’t exist already), which will contain the file prefixed with timestamp and migration file name which contains the below content:

def change
  change_column(:table_name, :column_name, :new_type)
end

Rails Guide – Changing Columns

A longer but safer method

The above code prevents the user from ever rolling back the migration. You can avoid this problem by splitting the change method into separate up and down methods:

def up
  change_column :my_table, :my_column, :new_type
end

def down
  change_column :my_table, :my_column, :old_type
end


Got any Ruby on Rails Question?