Web Development

Rails has given us a very easy way to create, add columns, change data types on our tables. Everything can’t be done for us. There are still some glitches, especially when there are database specific functionalities.

PG::DatatypeMismatch: ERROR: column “column_name” cannot be cast automatically to type integer
HINT: You might need to specify “USING column_name::integer”.

The above problem shows when you change a string column to an integer column. What’s a Rails programmer going to do? Change the migration.

def up
  change_column :table_name, :column_name, :integer
end
def down
  change_column :table_name, :column_name, :string
end
def up
  change_column :table_name, :column_name, 'integer USING CAST(incident_id AS integer)'
end
def down
  change_column :table_name, :column_name, :string
end

Voila! Fixed!

== 20160812114845 ChangeDataTypeOfColumn: migrating 
-- change_column(:table_name, :column_name, "integer USING CAST(incident_id AS integer)")
   -> 0.0279s
== 20160812114845 ChangeDataTypeOfColumn: migrated (0.0281s)