I have a small table and a certain field contains the type "character varying". I'm trying to change it to "Integer" but it gives an error that casting is not possible.
Is there a way around this or should I just create another table and bring the records into it using a query.
The field contains only integer values.
This question is related to
postgresql
casting
postgresql-9.1
fieldtype
You can do it like:
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
or try this:
change_column :table_name, :column_name, :integer, using: 'column_name::integer'
If you are interested to find more about this topic read this article: https://kolosek.com/rails-change-database-column
If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):
UPDATE the_table SET col_name = replace(col_name, 'some_string', '');
Try this, it will work for sure.
When writing Rails migrations to convert a string column to an integer you'd usually say:
change_column :table_name, :column_name, :integer
However, PostgreSQL will complain:
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:
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).
this worked for me.
change varchar column to int
change_column :table_name, :column_name, :integer
got:
PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.
chnged to
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)
If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.
UPDATE table_mame SET field_name= 0;
After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.
ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;
I think it will help you.
I had the same issue. I started to reset the default of the column.
change_column :users, :column_name, :boolean, default: nil
change_column :users, :column_name, :integer, using: 'column_name::integer', default: 0, null: false
Source: Stackoverflow.com