rails/rails — Issue #4840: ActiveRecord::Store does not work properly with a nullable db column.
Author: ihid
Created: 2012-02-01 23:51:11+00:00
State: open

The following code works fine if there is a db column called 'properties' which is text and nullable:

```ruby
class Tutorial
store :properties, accessors: [:width, :height]
end
t = Tutorial.new
t.width = 100
```

However, it fails if the column is not null, with:

```
TypeError: can't convert Symbol into Integer
from /Users/iHiD/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/store.rb:39:in `[]='
```

This can be reproduced in ActiveRecord tests by amending ```activerecord/test/schema/schema.rb:40``` to

```
t.text :settings, :null => false, :default => ""
```

The issue is clearly that the property is being initialized to a string, rather than an empty hash.

I think the fix can be written into ```activerecord/lib/active_record/attribute_methods/serialization.rb``` in 'initialize_attributes'.

A quick, dirty hack of changing line 67 to the following fixes the problem, but breaks other tests.

```ruby

current_value = attributes[key]
if coder.is_a?(Coders::YAMLColumn) && !current_value.is_a?(coder.object_class)
current_value = coder.object_class.new
end
attributes[key] = Attribute.new(coder, current_value, :serialized)
```

I am happy to look into this further, but I figure someone who knows this chunk of code will understand the full initialization process much more fully and so may be able to come up with a more robust solution.