I have a Rails model class with a serialized Hash attribute, like this:
class Action
serialize :metadata, Hash
# . . .
end
That column is stored in a text column with a YAML encoding. The problem is that when I pass a metadata value to the create! method, the hash keys are converted from symbols to strings, but that conversion doesn’t happen other times. For example:
$ rails console
> a = Action.create!(:metadata => {:foo => "bar"})
> a.metadata
=> {"foo"=>"bar"}
> a.metadata[:fizz] = "buzz"
> a.metadata
=> {"foo"=>"bar", :fizz=>"buzz"}
Now when I save the model, the database is going to have this text value:
---
foo: bar
:fizz: buzz
Any suggestions how to fix this?
(This is with Rails 3.0.16.)
Going to answer this myself, with a variant of @Mori’s suggestion:
As far as I can tell, this works around the problem without breaking the interface elsewhere. I guess if I wanted a key to be a string, this method would cause me a nasty surprise, but that’s not the case, so I’m more willing to accept it than the surprises raised by other proposed solutions.
Btw, if someone can propose a solution that doesn’t require this sort of workaround at all, I’ll happily accept that as the correct answer instead.