Pages

Monday, May 12, 2014

Irreversible Migrations in Ruby on Rails

In Rails 2 in migrations there were only 2 methods: up and down. They are called on running migrations up and down respectively with rake tasks rake db:migrate and rake db:rollback.

In Rails 2

def up
add_column :users, :active, :boolean User.update_all(active: true) end

def down remove_column :users, :active end

Rails 3 produced us great method change which allowed us to write there code which creates a table and drops the table automatically on rolling migration back. But unfortunately there was a problem – you didn’t have opportunity to say “don’t run this peace of code on down but run this only on up”. So the solution was just to use old syntax. 

In Rails 3

def change add_column :users, :active, :boolean end

Since Rails 4 has released there is a feature to fix this situation.

In Rails 4

Rails 4 provides us one more useful way to write what we need in one place:

def change add_column :users, :active, :boolean reversible do |direction| direction.up { User.update_all(active: true) } end end

For More Details visit http://www.codebeerstartups.com

1 comment: