exlibris asked tonight in #rubyonrails how to find the type of a column in the table for a model. I didn’t know this and maybe someone else out there may not know how either. The solution lies within the columns_hash method from ActiveRecord:Base which returns a hash containing all kinds of useful information about all the columns in your table such as:
- Precision (integer, notes the precision of the column if it's decimal-based)
- Primary (boolean, identifies if column is primary key)
- default
- limit (integer, denotes how long the field can be)
- type (symbol, the class type in lowercase)
- name (string, fairly obvious)
- null (boolean, identifies if column can be set to null)
- scale (integer, does something)
- sql_type (returns the sql type of the column)
That final column is the magic attribute we’re looking for. To get to it we access it like Model.columns_hash[“attribute”].sql_type