How to check if a table already exists in rails?

less than 1 minute read

Developers often need to check if a table already exists in the database schema. Rails provides built-in method to accomplish this effectively.

Syntax

table_exists?(table_name)

Example

Here is an example of how to use table_exists? method:

class CreateUsers < ActiveRecord::Migration[7.1]
  def change
    unless table_exists?(:users)
      create_table(:users) do |t|
        t.column :name, :string
        t.column :email, :string, null: false

        t.timestamps
      end
    end
  end
end

NOTE: This can also be re-written using the if_not_exists option in the create_table method.

class CreateUsers < ActiveRecord::Migration[7.1]
  def change
    create_table(:users, if_not_exists: true) do |t|
      t.column :name, :string
      t.column :email, :string, null: false

      t.timestamps
    end
  end
end

References