ActiveRecord returning Strings with find_by_sql?


#1

Hello,

I’m new to Ruby & Rails, and I’m trying to figure out if this
behavior by ActiveRecord is by design, or if I’m doing something
incorrectly. Here’s the deal: I have a class based on
ActiveRecord::Base that defines a method that creates a query using
find_by_sql(). The fields retrieved by joins with other tables are
being returned as Strings, regardless of field type. Fields from the
table that the class directly corresponds to are being returned as
whatever type is appropriate. Is that how it’s supposed to work? I
find myself having to do a lot of conversions when I need to perform
any math on the results obtained from this query.

Thanks for your help,

Mike Marcus
Software Engineer
Broadband.com
removed_email_address@domain.invalid


#2

Mike Marcus wrote:

to do a lot of conversions when I need to perform any math on the
results obtained from this query.

Thanks for your help,

It’s a long known deficiency of the current ActiveRecord implementation
(http://dev.rubyonrails.org/ticket/240). Likely not to change very soon.

– stefan


For rails performance tuning, see: http://railsexpress.de/blog
Subscription: http://railsexpress.de/blog/xml/rss20/feed.xml


#3

Mike Marcus wrote:

I’m new to Ruby & Rails, and I’m trying to figure out if this behavior
by ActiveRecord is by design, or if I’m doing something incorrectly.
Here’s the deal: I have a class based on ActiveRecord::Base that
defines a method that creates a query using find_by_sql(). The fields
retrieved by joins with other tables are being returned as Strings,
regardless of field type. Fields from the table that the class directly
corresponds to are being returned as whatever type is appropriate. Is
that how it’s supposed to work? I find myself having to do a lot of
conversions when I need to perform any math on the results obtained
from this query.

That’s how it works. You only get automatic casting for fields in
the model on which find is called, and only for fields from joined
tables when you use find’s :include option.

You can however define custom reader and writer methods for the
joined fields so that you only have to write the casting code once.


We develop, watch us RoR, in numbers too big to ignore.


#4

Thanks, Mark and Stefan for your replies!

  • Mike