Reputation: 8831
I store a hash to the mysql,but the result make me confuse:
hash:
{:unique_id=>35, :description=>nil, :title=>{"all"=>"test", "en"=>"test"}...}
and I use the serialize in my model.
serialize :title
The result in mysql like this:
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
all: test
en: test
Anyone can tell me what is the meaning? Why there is a ruby/hash:ActiveSupport::HashWithIndifferentAccess
in mysql?
Upvotes: 2
Views: 2579
Reputation: 121020
TL;DR:
serialize :title, Hash
What’s happening here is that serialize
internally will yaml-dump the class instance. And the hashes in rails are monkeypatched to may having an indifferent access. The latter means, that you are free to use both strings and respective symbols as it’s keys:
h = { 'a' => 42 }.with_indifferent_access
puts h[:a]
#⇒ 42
Upvotes: 3
Reputation: 11729
Hash needs to be serialized, default serializer is YAML which supports in some way, in the Ruby implementation, the storing of type. Your hash is of type ActiveSupport::HashWithIndifferentAccess, so when fetched back, ruby knows what object should get back (unserializes it to an HashWithIndifferentAccess).
Notice that HashWithIndifferentAccess is a hash where you can access values by using either strings or symbols, so:
tmp = { foo: 'bar' }.with_indifferent_access
tmp[:foo] # => 'bar'
tmp['foo'] # => 'bar'
With a normal hash (Hash.new
), you would get instead:
tmp = { foo: 'bar' }
tmp[:foo] # => 'bar'
tmp['foo'] # => nil
Obviously, in mysql, the hash is stored as a simple string, (YAML is plain text with a convention)
Upvotes: 1