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.
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:
Then you just run the rake task “db:migrate” and it will change the data type in the database table.




#1 by MikeL on March 30, 2010 - 6:44 pm
Quote
I always forget this to. Works great. Thanks!
#2 by The Ultimation on September 21, 2010 - 9:27 am
Quote
Good stuff, thanks!
#3 by John Goodman on November 2, 2010 - 7:48 am
Quote
Thanks, helped me out.
#4 by Fernando Magariños on January 17, 2011 - 6:05 pm
Quote
How would you test first if the column is of particular type? If you already have records with data in the old type, who does the copy/conversion from the old type to the new?
#5 by cowboycoded on January 17, 2011 - 8:26 pm
Quote
As far as I know, it just issues an “alter change” command on the database. So I guess it depends on what RDBMS you are using and how it reacts to “alter table change…”. For instance, if you are using mysql it would issue this command to your database:
ALTER TABLE widgets CHANGE count count float;
In this case there would be no data loss since its converting from int to float, but if you were converting a “text” type to “string” you would lose data. So it may be desirable to perform some data manipulation on the data before/after you run the migration, depending on what your scenario is.
To find the column type, you can use this:
#6 by Fernando Magariños on March 8, 2011 - 4:00 pm
Quote
Thanks.
#7 by Mandrake on July 22, 2011 - 7:52 am
Quote
Thanks man!
It’s works very well!
Good Job!
#8 by Kamikaze on October 24, 2011 - 8:45 am
Quote
Thanks for this; it was exactly what I was looking for.
Pingback: How to Change Data Format of Rails Field « My Ruby on Rails Learnings
#9 by Michael O'Boyle on February 13, 2012 - 11:28 am
Quote
Worked like a charm. Thanks!
#10 by mangala on June 6, 2012 - 5:13 am
Quote
Thanks a lot…………..
#11 by Nathan Lilienthal on July 12, 2012 - 9:08 pm
Quote
def change
change_table :users do |t|
t.change :phone, :string
end
end
this worked for me
#12 by Prakash Murthy on August 23, 2012 - 6:00 am
Quote
Awesome thanks! The post, and the comment clarifying the data-loss during conversion, were very helpful for me.
#13 by Juan on September 18, 2012 - 7:44 am
Quote
Genial, Muchas Gracias
#14 by Matt on October 27, 2012 - 10:32 am
Quote
Thanks