Rails 2.1 find_by_sql hides attributes

More headscratching. I created some kung-fu-panda SQL and tried to massage it into proper Rails format with the appropriate :select, :from, :conditions, etc, but that didn't work. So I resorted to find_by_sql(). It all seemed to work fine initially. But upon closer inspection I couldn't find my new special kung-fu columns (a.k.a attributes). As a stab in the dark I tried to access them in the console and there they were. They were just hidden. Let me show you:
Create a method something like this in one of your models:
def self.missing_attributes
self.find_by_sql("SELECT id, 'hello world' AS hw FROM mytable")

Then in the console, do, something like:
>> reload!
=> true
>> ma = Mytable.missing_attributes
=> [#<Mytable id: 1>, #<Mytable id: 2>, #<Mytable id: 3>, #<Mytable id: 4>]
>> ma[0].hw
=> "hello world"

As you can see from what's returned from the call to missing_attributes() is that the only attribute (a.k.a column) returned is the ID column... not so... accessing ma[0].hw will print out the correct value; "hello world" in this case.
I spent some time looking at the Rails bugs and couldn't find this, but when I tried to report it I couldn't find how to do it, so I gave up. I'm lazy. If you know how to report it, feel free.

No comments: