How to work with Git branches and Rails migrations How to work with Git branches and Rails migrations ruby-on-rails ruby-on-rails

How to work with Git branches and Rails migrations


When you add a new migration in any branch, run rake db:migrate and commit both the migration and db/schema.rb

If you do this, in development, you'll be able to switch to another branch that has a different set of migrations and simply run rake db:schema:load.

Note that this will recreate the entire database, and existing data will be lost.

You'll probably only want to run production off of one branch which you're very careful with, so these steps don't apply there (just run rake db:migrate as usual there). But in development, it should be no big deal to recreate the database from the schema, which is what rake db:schema:load will do.


If you have a large database that you can't readily reproduce, then I'd recommend using the normal migration tools. If you want a simple process, this is what I'd recommend:

  • Before switching branches, rollback (rake db:rollback) to the state before the branch point. Then, after switching branches, run db:migrate. This is mathematically correct, and as long as you write down scripts, it will work.
  • If you forget to do this before switching branches, in general you can safely switch back, rollback, and switch again, so I think as a workflow, it's feasible.
  • If you have dependencies between migrations in different branches... well, you'll have to think hard.


Here's a script I wrote for switching between branches that contain different migrations:

https://gist.github.com/4076864

It won't solve all the problems you mentioned, but given a branch name it will:

  1. Roll back any migrations on your current branch which do not exist on the given branch
  2. Discard any changes to the db/schema.rb file
  3. Check out the given branch
  4. Run any new migrations existing in the given branch
  5. Update your test database

I find myself manually doing this all the time on our project, so I thought it'd be nice to automate the process.