views:

37

answers:

1

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.

+2  A: 

You can access the types of the columns by doing this:

#script/console
Driver.columns.each do {|c| puts c.type}

If you want to get a list of all column types in a particular Model, you could do:

Driver.columns.map(&:type) #get's them all
Driver.columns.map(&:type).uniq #get's the unique ones
Mike Trpcic
Thank you. I am guessing this won't be part of ActiveModel though as it is bound to columns (which probably won't make it to AM). But that works just awesome for AR. You know I actually knew that at the back of my mind, but for some reason blocked it out.
Michael Neale