Getting types of the attributes in an ActiveRecord object

In Rails 5, you can do this independently of the Database. That's important if you use the new Attributes API to define (additional) attributes.

Getting all attributes from a model class:

pry> User.attribute_names
=> ["id",
 "firstname",
 "lastname",
 "created_at",
 "updated_at",
 "email",...

Getting the type:

pry> User.type_for_attribute('email')
=> #<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x007ffbab107698
 @limit=255,
 @precision=nil,
 @scale=nil>

That's sometimes more information than needed. There's a convenience function that maps all these types down to a core set (:integer, :string etc.)

> User.type_for_attribute('email').type
=> :string 

You can also get all that data in one call with attribute_types which returns a 'name': type hash.


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