Getting types of the attributes in an ActiveRecord object

Michael Neale picture Michael Neale · Mar 8, 2010 · Viewed 46k times · Source

I would like to know if it is possible to get the types (as known by AR - eg in the migration script and database) programmatically (I know the data exists in there somewhere).

For example, I can deal with all the attribute names:

ar.attribute_names.each { |name| puts name }

.attributes just returns a mapping of the names to their current values (eg no type info if the field isn't set).

Some places I have seen it with the type information:

in script/console, type the name of an AR entity:

>> Driver
=> Driver(id: integer, name: string, created_at: datetime, updated_at: datetime)

So clearly it knows the types. Also, there is .column_for_attribute, which takes an attr name and returns a column object - which has the type buried in the underlying database column object, but it doesn't appear to be a clean way to get it.

I would also be interested in if there is a way that is friendly for the new "ActiveModel" that is coming (rails3) and is decoupled from database specifics (but perhaps type info will not be part of it, I can't seem to find out if it is).

Thanks.

Answer

Grant Birchmeier picture Grant Birchmeier · Mar 27, 2013

In Rails 3, for your model "Driver", you want Driver.columns_hash.

Driver.columns_hash["name"].type  #returns :string

If you want to iterate through them, you'd do something like this:

Driver.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}

which will output the following:

id => integer
name => string
created_at => datetime
updated_at => datetime