Rails Migration to convert string to integer? Rails Migration to convert string to integer? database database

Rails Migration to convert string to integer?


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


The other answers are correct, yet you can take one step further with the :using keyword:

change_column :people, :company_id, :integer, using: 'company_id::integer'


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.