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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With