atw
atw

Reputation: 5840

Rails: Effects of changing the data type of an existing column with existing data

I could be asking this in the wrong place so go easy and point me in the right direction if I am.

I can't get my head around how changing the data type of an existing column in an existing table with existing data in Rails will effect any app I am working on.

If I have a boolean column called football. The football can be either true or false. Either, I have a football or I don't. I realise that, for example, the football can sometimes be loaned. So, I want to change the data type of the column football to be a string. The value of the string can be true, false or loaned.

How bad a time am I going to have after running the migration for this? What will happen to my existing data? What do I need to do to mitigate against messing up all my existing data? And, am I asking this question in the right place?

Upvotes: 2

Views: 1124

Answers (2)

rlarcombe
rlarcombe

Reputation: 2986

If I were you I would do this by creating a new column, then updating everything from the old column, and then removing the old column, and renaming the new one. Also I wouldn't save a boolean as "true" or "false" either (which Rails should give you by default if you DO just change the type)... If I were you I would create an enum for this column.

First your migration:

class ChangeFootball < ActiveRecord::Migration
  def change

    # Add the new column. Use an integer type, so you can set up an Enum in your model
    add_column :examples, :football_new, :integer, default: 0

    # Set up the new column values for all your existing records:
    Example.where(football: true).update_all football_new: 0
    Example.where(football: false).update_all football_new: 1

    # Now remove the old column:
    remove_column :examples, :football

    # Finally, rename the new column to the same as the old one
    rename_column :examples, :football_new, :football

    # Oh, and add an index:
    add_index :examples, :football
  end
end

Now set up the enum in your model:

enum football: { own: 0, lost: 1, misplaced: 2, loaned: 3 } 

Upvotes: 2

Qubaish Bhatti
Qubaish Bhatti

Reputation: 728

If you change the column type from boolean to string in rails then you have no worry because the existing data will automatically change into string. Like if you have boolean true this will automatically convert into string "true".

FYI, I checked this on my system ;)

Upvotes: 2

Related Questions