Change a column data type with Rails migration

I always forget the syntax for this and I have to look it up, so I am going to post it here.  Maybe this will help some others out.  Basically, what I need to do is change the data type of a column in my database table.  The table “widgets” contains a column/field named “count”.  I want to change count from an integer to a float.  So first I create a rails migration with the following command.

>script/generate migration change_data_type_for_widget_count

Then I edit the migration file:   app_root/db/migrate/20091007151516_change_data_type_for_widget_count.rb.  Here is the migration syntax to change the data type of a column:

class ChangeDataTypeForWidgetCount < ActiveRecord::Migration
  def self.up
    change_table :widgets do |t|
      t.change :count, :float
    end
  end

  def self.down
    #.....
  end
end

Then you just run the rake task “db:migrate” and it will change the data type in the database table.

>rake db:migrate

Leave a Reply