Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Migration to convert string to integer using conversion

Tags:

There is a good question here I want to elaborate on. I am trying to convert a column in my database form a string to an integer.

I thought the conversion would be pretty straight forwrad. Currently my strings are

["10", "12", "125", "135", "140", ...]

My migration file includes:

def change
    change_column :table_name, :product_code, :integer
end

Rails tries this but Postgresql thows back an error.

PG::Error: ERROR: column "product_code" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.

I am not sure how I use this 'USING' expression in my rails migration.

So I thought the conversion would be pretty straight forward. What should I use as the USING expression?

like image 781
Jay Killeen Avatar asked Mar 14 '14 01:03

Jay Killeen


People also ask

How do I migrate a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

What does db Migrate do rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

How does Rails migration work internally?

Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them.

What is reversible migration in Rails?

Reversible Migrations Rails allows us to rollback changes to the database with the following command. rails db:rollback. This command reverts the last migration that was run on the database. If the migration added a column event_type then the rollback will remove that column.


1 Answers

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

Source: http://makandracards.com/makandra/18691-postgresql-vs-rails-migration-how-to-change-columns-from-string-to-integer

like image 180
Björn Nilsson Avatar answered Sep 19 '22 11:09

Björn Nilsson