Pages

Wednesday, September 28, 2011


How to change the data type for a given columns using Migrations


I have a users database table. There's an attribute, 'admin' which reflects if a given user is an administrator or not. It's now time to implement features in the application which would act based on whether a user is an administrator or not. While we could have got away with the admin attribute being an integer of either zero or one, setting it as a boolean data type would be better suited to the nature of the attribute being used.

1) generate a new migration

[rails3]$ rails generate migration change_data_type_for_admin_in_users_table
      invoke  active_record
      create    db/migrate/20110927235341_change_data_type_for_admin_in_users_table.rb


2) edit the migration file and use the change_column() method. This method does allow options to
set the default value of the attribute. In this case, I set it to false such that all new users are not administrators by default
Notice that I deleted the self.down method definition. This is because in the case of a db rollback, nothing needs to be done to this attribute.
I would expect the user database table to be dropped and that's it.


class ChangeDataTypeForAdminInUsersTable < ActiveRecord::Migration  def self.up        change_column(:users, :admin, :boolean, :default => false)  endend



3) run the migration


[rails3]$ rake db:migrate
==  ChangeDataTypeForAdminInUsersTable: migrating =============================
-- change_column(:users, :admin, :boolean, {:default=>false})
   -> 0.3049s
==  ChangeDataTypeForAdminInUsersTable: migrated (0.3052s) ====================
s_table.rb$ git add db/migrate/20110927235341_change_data_type_for_admin_in_user


4) done