views:

75

answers:

2

I have a legacy database that has integer data stored as chars that I would like to treat as numerical. Is there a quick and easy way to convert this is one place? The values are from 0-5 and it defaults to 0 so there are no nulls.

I can't just fix the data because the legacy db will still be updated by the legacy app.

So I am basically wondering if there is some activerecord option that could automatically cast the column.

+3  A: 

You could override the column name with a method that converts the char to an integer

e.g.

def my_col
   read_attribute(:my_col).to_i
end

Then it should work pretty much seamlessly

DanSingerman
+1  A: 

There is a section in the ActiveRecord::Base docs called "Overwriting default accessors" that talks about just this scenario:

All column values are automatically available through basic accessors on the Active Record object, but sometimes you want to specialize this behavior. This can be done by overwriting the default accessors (using the same name as the attribute) and calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.

There is an alternate hash-style syntax mentioned as well.

Will Green