Finding SQL Type of Column

December 14th, 2008 by Radar

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 columnshash 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)
  • sqltype (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.columnshash["attribute"].sqltype

Tags:

Leave a Reply