checking table existence in Rails’ migrations

I just refactored a table and in the migration I created for it I first need to drop the table and then create it from scratch, so the first line of self.up is drop_table :table_name. But when I go back and forth over that migration, the second time around the table doesn’t exist (because it got dropped proper in self.down), so I need to check that the table exists before I try to drop it in self.up.

Here’s the function I created to do that check:

 def self.table_exists?(name)
    ActiveRecord::Base.connection.tables.include?(name)
  end

And here’s the new first line of self.up:
drop_table :table_name if self.table_exists?("table_name")

Clean.

27 March 2008 | general, projects, ruby | Comments

Leave a Reply

  1.  
  2.  
  3.  

About Me

I work at outside.in during the day. On nights and weekends I do stuff and work on side projects, which you can read about here.
View my outside.in blogmap.

    Meta