Changing Columns in a Database Table with Migrations in Rails
Learn how to alter columns in a database table using the migration generator in a Ruby on Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So, what happens when you want to change an existing value in your database?

For example, in my projects table, I want to change the data type of the field stage from an integer to a string data type because I don't want to have numbers, I'd prefer to have words instead.

To do that, go to your console and type:

rails g migration change_data_type_for_stage

This command will create a migration file.

large

Now, open the up the migration file 20151030005157_change_data_type_for_stage.rb

large

Unlike how the migration generator worked when we were adding a column to a table, this method is not going to have any code inside the change method for us, so we have to add it manually. The code you need to add inside the change method will look like this:

def change
  change_column :projects :stage :string
end

In this code, we are calling the method change_column, and passing the parameters projects which is the table name, stage which is the field name and string is the new data type we want.

If you go back to rails, and run the migrate command

rake db:migrate

Now, if you go to your schema file, the data type of the stage field has been changed.

large

You're likely to be doing this task many times in your projects, so it's good to know how to do it. An important item to note here. DO NOT do this on a production application, it will erase all of the data in that column. If you are doing this for a production application, create a new column, then write a script that copies the values over to that column and convert them to the new type. Then you can delete the old column. If you follow this process you won't lose any data.