Skip to content

checking table existence in Rails' migrations

by cory on March 27th, 2008
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.

From → general, projects, ruby

8 Comments
  1. Couldn't you use AR's table_exists? method?

  2. William A Iuchs permalink

    nice article! nice site. you're in my rss feed now ;-)
    keep it up

  3. Jean J Abts permalink

    you are on my rss reader now

  4. Here's something quick to check for a column:
    Model.columns_hash.has_key("column_name")?

  5. patelc75 permalink

    Actually, it should be
    Model.columns_hash.has_key?("column_name")

  6. Here is my approach to solve the problem:

    http://github.com/rafmagana/database_utils

    after using that code you can do this in a migration:

    :users.table_exists?
    "users".table_exists?
    :users.column_exists? :name

    see you

  7. Here is my approach to solve the problem:

    http://github.com/rafmagana/da...

    after using that code you can do this in a migration:

    :users.table_exists?

    "users".table_exists?

    :users.column_exists? :name

    see you

  8. You could also use Rails' built-in force parameter:

    create_table :some_table, :force => true do |t|
      t.integer user_id, :null => false
    end

    This forces a new table to be created even if a current table with that name exists.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS