We build Web & Mobile Applications.

< All Articles

Accessing column information with ActiveRecord

A quick tip - ActiveRecord provides a number of methods that allow you to access information about the underlying table columns for a model.

columns
Returns an array of Column objects.
columns_hash
Similar to the columns method but returns a Hash using column names as keys and Column objects as values.
column_names
Returns a simple array of column names for the model.

The Column objects returned by columns and columns_hash can then be used to get information such as the data type and default values, for example:

User.columns_hash['email'].type
=> :string
User.columns_hash['email'].default
=> nil
User.columns_hash['email'].sql_type
=> "varchar(255)"
Updated on 07 February 2019
First published by Chris Anderton on 14 April 2009
© Chris Anderton 2019
"Accessing column information with ActiveRecord" by Chris Anderton at TheWebFellas is licensed under a Creative Commons Attribution 4.0 International License.