Wednesday, September 30, 2009

Remove Default in Rails Migration

Here is an example of how to remove a :default in a Rails migration (based on solution here that does same except that one also includes making the column NOT NULL at same time):

class RemoveDefaultFromSomeAttribute < ActiveRecord::Migration

  # from similar solution at http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/126ea36cdd559ec9
  def self.up
    add_column :name_of_my_model, :temp_name_of_my_attribute, :string
    #store names on new temp_name_of_my_attribute column
    NameOfMyModel.find(:all).each do |b|
      b.temp_name_of_my_attribute = b.name_of_my_attribute
      b.save!
    end
    remove_column :name_of_my_model, :name_of_my_attribute
    rename_column :name_of_my_model, :temp_name_of_my_attribute, :name_of_my_attribute
  end

  def self.down
    add_column :name_of_my_model, :temp_name_of_my_attribute, :string, :default => 'some_old_default_value'
    #store names on new temp_name_of_my_attribute column
    NameOfMyModel.find(:all).each do |b|
      b.temp_name_of_my_attribute = b.name_of_my_attribute
      b.save!
    end
    remove_column :name_of_my_model, :name_of_my_attribute
    rename_column :name_of_my_model, :temp_name_of_my_attribute, :name_of_my_attribute
  end
end

2 comments:

Thomas said...

This was really helpful, thanks! I believe there is an extra comma in self.down in the add_column.

Gary S. Weaver said...

Just made that fix to the post. Thanks!