Monday, December 17, 2007

Auto reverting Migrations

I often end up writing some code in self.up that craps out and it is painful to reverse any database changes that may have been committed. I often resort to revert to an earlier version, but that is an extra step I would rather not have to do.

I make sure all the extra code is located after any database changes I want to make and then wrap the whole shebang in a begin-rescue block:

class FixCategoriesOrder < ActiveRecord::Migration
def self.up
begin
add_column :categories, :sort_order, :integer
# ... other database changes

# Code
[["Immunology", 1],
["Biochemistry", 2],
["Biotechnology", 3],
["Cell Biology", 4],
["Genomics", 5],
["Plant Biology", 6],
["Developmental Biology", 7],
["Ecology", 8],
["Other", 100]].each do |ar|
puts "Processing #{ar[0]} - #{ar[1]}"
Category.find_by_name(ar[0]).update_attribute(:sort_order, ar[1])
end
rescue
self.down
raise $!
end

end

def self.down
remove_column :categories, :sort_order
end
end



Njoy

No comments: