method

column_exists?

rails latest stable - Class: ActiveRecord::ConnectionAdapters::SchemaStatements
column_exists?(table_name, column_name, type = nil, **options)
public

Checks to see if a column exists in a given table.

# Check a column exists
column_exists?(:suppliers, :name)

# Check a column exists of a particular type
#
# This works for standard non-casted types (eg. string) but is unreliable
# for types that may get cast to something else (eg. char, bigint).
column_exists?(:suppliers, :name, :string)

# Check a column exists with a specific definition
column_exists?(:suppliers, :name, :string, limit: 100)
column_exists?(:suppliers, :name, :string, default: 'default')
column_exists?(:suppliers, :name, :string, null: false)
column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)

2Notes

Example

stevo · Jan 20, 20121 thank

Check if id column exists in users table

ActiveRecord::Base.connection.column_exists?(:users, :id)

It also works with strings

jonathonjones · Feb 20, 2013

It works with strings:

ActiveRecord::Base.connection.column_exists?('users', 'id')

Which is helpful if you need to specify the database/schema to use:

ActiveRecord::Base.connection.column_exists?('secondary.users', 'id')