Posted over 6 years ago. Visible to the public.

PostgreSQL vs. Rails migration: How to change columns from string to integer

When writing Rails migrations to convert a string column to an integer you'd usually say:

Copy
change_column :table_name, :column_name, :integer

However, PostgreSQL will complain:

Copy
PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer HINT: 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:

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

The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
over 6 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more