Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Migration to convert string to integer?

Is it possible to change a field that's a string to an integer without clearing the data already entered?

The current db structure for the table in question is:

create_table :people do |t| t.string :company_id 

Is this possible using migrations?

I'm thinking maybe in the migration drop the old field, create a new one that's an integer - but I'm worried this will clear all of the data already entered.

Thanks,

Danny

like image 646
dannymcc Avatar asked Aug 21 '10 09:08

dannymcc


1 Answers

Don't drop the column, use this

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)' 

The "hint" you got from PostgreSQL basically tells you that you need to confirm you want this to happen, and how data should be converted. To confirm the changes, use the block above in your migration

like image 88
user3402754 Avatar answered Oct 14 '22 00:10

user3402754