ActiveRecord attributes -- strange behavior when adding Arra

Hi,

I have a database table and associated ActiveRecord model. I was
trying to store (temporarily) an array in one of the attribute
elements - not to save it, but just so that I can keep some form data
in a sensible place. A stripped down version of the problem I’m having
is:

p = Property.new(:bedroom_count => [“2”,“3”])
puts p.inspect # ==> will correctly show that the array is stored in
the attributes “hash”
puts p.bedroom_count # => returns 1

I realize I’m a little “off rails” on this approach, but does anyone
have any knowledge of what’s going on in this case?

Thanks,

Steve

On Mar 30, 2007, at 1:40 AM, Steve M. wrote:

I realize I’m a little “off rails” on this approach, but does anyone
have any knowledge of what’s going on in this case?

The behaviour you are seeing comes from the fact that the generated
getters call to ActiveRecord::ConnectionAdapters::Column#type_cast
via ActiveRecord::Base#read_attribute:

def read_attribute(attr_name)
attr_name = attr_name.to_s
if !(value = @attributes[attr_name]).nil?
if column = column_for_attribute(attr_name)
if unserializable_attribute?(attr_name, column)
unserialize_attribute(attr_name)
else
column.type_cast(value)
end
else
value
end
else
nil
end
end

Note that this is an attribute reader, and so does not reset the
underlying value. Thus, you can always get the original object using

p.bedroom_count_before_typecast

Once understood, assigning an array to a field that is supposed to
hold an integer is really suspicious, does it really make sense in
your context?

– fxn