Broom

How to clean up your ActiveRecord migrations

Migrations in Ruby on Rails allow you to alter your database using a convenient and easy DSL.  When I started using Rails, migrations were a breath of fresh air. Database schema were finally easy. No longer did I have to pass SQL scripts to developers to run against their development DB or make a huge script to run at deployment. Migrations took care of this. However the problem with migrations is that after a while, a huge amount of migration files build up in your project. Below are detailed steps on how to clean up your migrations to make managing them easier.

Step 1: Ensure you include db/schema.rb in your SCM

The file db/schema.rb is the current definition of your database. It is versioned and updated after a migration is run. This file is essential in creating your database once all your older migrations are gone. Remember that db/schema.rb is db agnostic, so any implementation specific db statements in your migrations will not exist in the schema.

Step 2: Migrate to the latest version

Notify your team to checkout the latest version of your project and migrate. This will ensure that future migrations will continue to run smoothly on their current development database.

Step 3: Seed your database with db/seeds.rb

Go through each of your migrations and ensure that no data is being inserted in any of them. Migrations are only supposed to be used to manipulate the structure of your database, not populate it.  Rails provides a file db/seeds.rb where you can run ruby code and model creation statements to set all the data required by your application to start.

Below is an example of a db/seeds.rb file setting up the users of a system:

User.create [{ :name => ‘admin’ }, { :name => ‘foo’ }, { :name => ‘bar’ }]

You can populate your database with seed data anytime by running rake db:seed. Seeding was added in Ruby on Rails 2.3.4.

Step 4:  Keep only latest migrations

Go to db/migrate folder and delete all but your latest migration or move the older migrations to a folder such as db/archieved_migrations. You will want to keep the last migration as a reference if you need to migrate down.

Step 5: Setting up a fresh environment

Even though all your migrations are gone except for one, a developer can setup a fresh environment with a development database containing all required data by running one rake task: rake db:setup. This task will create the database, load the entire schema from db/schema.rb, and then populate the database based on db/seeds.rb.

Creative Commons: