I have a model, let’s call it “User”. It has a field named “age” and it’s an int
When I do:
user = User.find(:all, :select => "age").first
age = user.age
I get the age back as a string, even though it’s an integer column.
I know I can easily do age.to_i to get an integer, but sometimes I forget, and it turns to a bug downstream as I end up comparing a string to an integer.
How do I make find, and select return an actual integer when the column is an int? When I use User.where, it does return an actual integer. I want User.find to behave the same exact way.
Typecasting, and many other transformations on data that comes form the database, can be done by writing a method for the attribute in question, and directly accessing the attributes to transform them.
You might also want to do this when converting a string to symbol, or to use BigDecimal for currencies, for example. In some cases, writing a custom setter method will also be required.
I’m sure there’s a gem out there where you could define typecasts on attributes to have these methods generated automatically for you.