Awkward and Proud

Rails migrations - Checking the existence of a table

Recently, I had to drop a table because I no longer needed the model at all. However, working on a distributed team, there were other folks with varying levels of “migration” status for their databases. A first migration to drop the table would be simply the following:

However, I also wanted to get rid of the original migration file that created the file to begin with, since it was no longer meaningful. As it turns out, checking the existence of a table isn’t complicated at all:

Now, folks who never had that table to begin with won’t get an error when running rake db:migrate, and those who did will simply drop it. This works because connection is actually delegated to ActiveRecord::Base.connection.

As a disclaimer, I’ve only used this technique in Rails 2.3, so I can’t vouch for it working in other versions.