Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord converts symbol keys to strings when serializing my hash

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.)

like image 858
Paul A Jungwirth Avatar asked Sep 18 '12 19:09

Paul A Jungwirth


1 Answers

class Action < ActiveRecord::Base
  def metadata
    self[:metadata].try :symbolize_keys
  end
end
like image 154
Mori Avatar answered Oct 08 '22 13:10

Mori