Rails Migration to convert string to integer using conversion Rails Migration to convert string to integer using conversion postgresql postgresql

Rails Migration to convert string to integer using conversion


Adjusted code to support converting blank strings, too:

change_column :table_name, :product_code,   "integer USING NULLIF(product_code, '')::int"

Empty string becomes NULL, which becomes 0 on type conversion, which is probably the best you can do in this situation.


When you write Rails migrations to convert a string column to an integer you'd usually write like this:

change_column :table_name, :column_name, :integer

You might get this:

PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integerHINT:  Specify a USING expression to perform the conversion.

The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:

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