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.)
class Action < ActiveRecord::Base
def metadata
self[:metadata].try :symbolize_keys
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With