Ruby on Rails Schema Migration using schema.rb

A few months ago, we had a problem. We had a (relatively) mature application we wanted to deploy to a new server. In this case, waited to deploy to the production server until after several weeks of development/testing in stage. We deployed via Webistrano, then we tried to deploy:migrate, and that’s where things went south.

Migrations that were written and worked with version X of our app failed 10 versions down the road. You’re especially vulnerable when something that was a model attribute (ergo, a table field) before is now an instance method, or vice versa. For example, maybe password starts out as an attribute, but later becomes a method because you want password=(x) to generate a hash.

If you’re doing a fresh setup on a new server, and your app has been through several migrations already, you should ditch migrations for the initial deploy and run db/schema.rb instead, with the command rake db:schema:load. It will create the latest version of your database schema, including the current version number so future migrations will run without a problem.

There is even a note about this in db/schema.rb itself, which I just found today:

helpful hint provided in schema.rb itself
  Note that this schema.rb definition is the authoritative source for your
  database schema. If you need to create the application database on another
  system, you should be using db:schema:load, not running all the migrations
  from scratch. The latter is a flawed and unsustainable approach (the more
  migrations you'll amass, the slower it'll run and the greater likelihood
  for issues).

Also, db/schema.rb is a great place to see the current state of your tables! Just this morning I returned to a dusty project, and needed to know what table fields already existed, and which I needed to add. In fact, that’s how I stumbled on the above notice.


Tags: , , , , ,

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: