# ActiveRecord attributes -- strange behavior when adding Arra

**URL:** <https://www.ruby-forum.com/t/activerecord-attributes-strange-behavior-when-adding-arra/90586>\
**Category:** Rails\
**Created:** [March 30, 2007, 1:41am UTC](https://www.ruby-forum.com/t/activerecord-attributes-strange-behavior-when-adding-arra/90586 "2007-03-30T01:41:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sjmadsen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b3f665/32.png) [@sjmadsen](https://www.ruby-forum.com/u/sjmadsen)\
**Post date:** [March 30, 2007, 1:41am UTC](https://www.ruby-forum.com/t/activerecord-attributes-strange-behavior-when-adding-arra/90586/1 "2007-03-30T01:41:30Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![sjmadsen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b3f665/32.png) [@sjmadsen](https://www.ruby-forum.com/u/sjmadsen)\
**Post date:** [March 30, 2007, 10:06am UTC](https://www.ruby-forum.com/t/activerecord-attributes-strange-behavior-when-adding-arra/90586/2 "2007-03-30T10:06:35Z")

</div>

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
