rails 3.1 Reversible Migrations

Migrations has been always one of the importnat features of Rails. With Rails 3.1 they got new , it no more up and down methods , there is only one method change .

if you look at any migration , there are couple of questions like “why class methods ?” , “why rails not taking care of reversing migration itself?”

this is what new approach is all about !

Aaron Patterson  simplified things !

The new Change method !

<code>

class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :title
t.text :description
t.string :image_url
t.decimal :price

t.timestamps
end
end
end

</code>

this is default migration for Models using change method , as you can see there is only up logic . When you want to do rollback , rails will figure out how to reverse the migration from understanding your up code .

But ofcource there are few things which cannot be automatically reversed , this is becuase inforamtion required to do so is not available. e.g remove_column . In such cases rails will rais exception “ActiveRecord::IrreversibleMigration" .

In this case manually define up and down method . but then it can be just simple instance methods and not class methods .

Do take a look at the code  to understand what is happening .

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s