Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: change column type, but keep data

I have a model with a column of type integer which I want to convert to type string. Now I'm looking for the best way to change the column type without losing the data. Is there a painless way to accomplish this?

like image 277
blissini Avatar asked Mar 02 '12 10:03

blissini


People also ask

How do you change the name of a column in Ruby on Rails?

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again: rename_column :table_name, :old_column1, :new_column1 rename_column :table_name, :old_column2, :new_column2 ...

What is irreversible migration?

The migration that cannot be undone: Irreversible Migration.


2 Answers

A standard migration using the change_column method will convert integers to strings without any data loss. rake db:rollback will also do the reverse migration without error if required.

Here is the test migration I used to confirm this behaviour:

class ChangeAgeToString < ActiveRecord::Migration   def self.up     change_column :users, :age, :string   end    def self.down     change_column :users, :age, :integer   end end 
like image 122
Jon Avatar answered Sep 18 '22 16:09

Jon


for postgres in migration

 change_column :table_name, :field,'boolean USING (CASE field WHEN \'your any string as true\' THEN \'t\'::boolean ELSE \'f\'::boolean END)' 

and to any valid type similar

like image 27
Денис Епишкин Avatar answered Sep 17 '22 16:09

Денис Епишкин