Last Updated: February 25, 2016
·
1.014K
· ritchiey

Using Multiple Rails Development Databases

Sometimes you're hacking away on a new feature in its own branch and for some reason you need to switch branches. Git was born to handle this so you checkout a new branch and all your working files update accordingly. Super.

Unfortunately your database doesn't update with the code. You're still using the same development database and it has schema changes so when you run:

rake db:migrate db:test:prepare

Your schema.rb gets updated with the schema for your new feature. This can break things, especially if you've added constraints.

You could create a new environment so you have:

  • development
  • other_development
  • test
  • production

But that's probably not a good option.

  • It affects other developers
  • You'll probably end up hacking in multiple places to work around this because...
  • It's not really a different environment

Multiple Working Copies

Some may prefer a solution based on Git branches. I decided to go with multiple working copies because (for me) it's faster to switch between them.

Git stash is cool but it has its limits. If I'm swapping branches frequently because I'm responsible for deploys or something, I find it easier just to have two working copies and have a separate virtual desktop for each so I don't get confused.

To do this, I edited database.yml and added:

<%
def prefix
  name_parts = File.basename(Dir.pwd).split('$')
  name_parts.count == 2 ? "#{name_parts.last}_" : ''
end
%>

And then under the development: section:

database: <%= "#{prefix}myproject_development" %>

With those changes in place, if I clone the repo to a directory with a $deploy suffix (eg myproject$deploy), it will expect the development database to be called deploy_myproject_development. Be aware that '$' is probably considered special by your shell so you'll need to quote it. For example:

git clone git@github.com:myaccount/myproject.git "myproject$deploy"

Obviously, you'll need to run rake db:setup again but after that you'll have two separate development databases and it will automatically choose the right one based the name of the directory containing the app.