Show database migration versions with Rake

Something I frequently need to do when deploying a Rails application is determine the current migration version of a database. In the past, I’ve done this by bringing up mySQL and typing:

SELECT version FROM schema_info

Well, I’m finally tired of doing that so I cooked up this Rake task:

namespace :db do
  desc "Print current database migration version to the console"
  task :version => :environment do
    puts "VERSION=#{ActiveRecord::Migrator.current_version}"

To install, copy and paste into lib/tasks/common.rake (or wherever you store your custom Rake tasks). Then fire up a terminal window and feel the power:

$ rake db:version
(in /Users/matt/project)

I’m surprised this isn’t already in Rails. Sure, there’s script/about, but I always forget to use it. It also spits out other information I don’t typically need to know.

Why care about the migration version in the first place? When you’re on a project with multiple Rails deployments (dev/test/prod) and multiple developers creating migrations in multiple branches, it comes in quite handy.