ActiveRecord oddity of the day

Yesterday I got bit by this fairly obscure behavior in ActiveRecord:

>> person = Person.first
=> #<Person id: 1, name: "Jakob", height: 170, created_at: "2010-01-22 08:57:02", updated_at: "2010-01-22 08:58:57">
>> person.height = 169,5
=> [169, 5]
>> person.height
=> 1

Uhm, huh? The above is from Rails 2.3.5 using SQLite, but I originally saw the issue running on PostgreSQL.

It turns out, that if the object you assign to an integer attribute/column does not respond to to_i, the attribute will be set to 1 - unless the object evaluates to false in which case the attribute will be set to 0.

My best guess is that ActiveRecord is trying to work around the lack of boolean columns in MySQL with this. So even though I am not using MySQL I still have to suffer its ineptitude. One just can’t win.

Comments

Chopmo January 22, 2010

Pretty obscure behaviour.

And I'm surprised that the assignment does not yield 1?

Ie. I would have expected:

>> person.height = 169,5
=> 1

DHH January 22, 2010

Note that 169,5 is declaring an inline array, not a floating point. And using a floating point for height is probably not a good idea in any circumstance. You want to use a decimal, if anything.

The correct behavior here probably should be an exception. PDI a patch ;)

Jakob S January 23, 2010

I realize that I am trying to assign an array to an integer, that was basically the bug I ran into.

The behavior is fairly odd, though, and it's good to hear that an exception might be warranted. I'll add it to my PDI list ;)

Commenting on this entry has been closed.