Codebeerstartups

Irreversible Migrations in Ruby on Rails

Introduction

user

Mohit Jain

Rails Developer


migrations ruby-on-rails

Irreversible Migrations in Ruby on Rails

Posted by Mohit Jain on .
Featured

migrations ruby-on-rails

Irreversible Migrations in Ruby on Rails

Posted by Mohit Jain on .

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.

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. Since Rails 4 has released there is a feature to fix this situation.

##In Rails 2

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

def down
  remove_column :users, :active
end

##In Rails 3

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

##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

Checkout the official documentation

user

Mohit Jain

http://codebeerstartups.com

Rails Developer