Check if a table exists in Rails Check if a table exists in Rails ruby ruby

Check if a table exists in Rails


In Rails 5 the API became explicit regarding tables/views, collectively data sources.

# Tables and viewsActiveRecord::Base.connection.data_sourcesActiveRecord::Base.connection.data_source_exists? 'kittens'# TablesActiveRecord::Base.connection.tablesActiveRecord::Base.connection.table_exists? 'kittens'# ViewsActiveRecord::Base.connection.viewsActiveRecord::Base.connection.view_exists? 'kittens'

In Rails 2, 3 & 4 the API is about tables.

# Listing of all tables and viewsActiveRecord::Base.connection.tables# Checks for existence of kittens table/view (Kitten model)ActiveRecord::Base.connection.table_exists? 'kittens'

Getting the status of migrations:

# Tells you all migrations runActiveRecord::Migrator.get_all_versions# Tells you the current schema versionActiveRecord::Migrator.current_version

If you need more APIs for migrations or metadata see:


even if table is not exists:

model Kitten, expected table kittensrails 3:

Kitten.table_exists? #=> false


I found this out while I was trying to remove a table via a migration:

drop_table :kittens if (table_exists? :kittens)ActiveRecord::Migration.drop_table :kittens if (ActiveRecord::Base.connection.table_exists? :kittens)

works for Rails 3.2

This simpler form will become available in Rails 5:

drop_table :kittens, if_exists: true

Reference: https://github.com/rails/rails/pull/16366

And here's the Rails 5 ActiveRecord's CHANGELOG:

Introduce the :if_exists option for drop_table.

Example:

drop_table(:posts, if_exists: true)

That would execute:

DROP TABLE IF EXISTS posts

If the table doesn't exist, if_exists: false (the default) raises an exception whereas if_exists: true does nothing.