views:

73

answers:

1

Hi Everyone,

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

+1  A: 

Do not drop the column, it will clear the data.

You can however try

change_column :people, :company_id, :integer

and if all values in company_id can be converted to integer, it should be fine.

If that is not the case (ie not all string can be converted by default), then you can do it in two steps: 1) create a new column, then load the company_id in there after some conversion. 2) drop company_id then rename the new column.

You should be careful with both methods (more so for the second one) and you should probably do it first on a copy of the database, if you can.

Zaki
thanks for improving the formatting, jigfox
Zaki
Great, thanks. I presume I don't have to state the current type in the first example?
dannymcc