我将散列存储到mysql,但结果使我感到困惑:
散列:
{:unique_id=>35, :description=>nil, :title=>{"all"=>"test", "en"=>"test"}...}并且在我的模型中使用序列化。
serialize :titlemysql的结果如下:
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
all: test
en: test有人能告诉我这是什么意思吗?为什么mysql中有一个ruby/hash:ActiveSupport::HashWithIndifferentAccess?
发布于 2015-07-21 11:41:10
TL;DR:
serialize :title, Hash这里发生的是serialize内部将yaml-转储类实例。并且rails中的散列被设置为可以有一个无动于衷的访问。后者的意思是,您可以自由地使用字符串和相应的符号作为它的键:
h = { 'a' => 42 }.with_indifferent_access
puts h[:a]
#⇒ 42发布于 2015-07-21 11:38:55
哈希需要序列化,默认序列化程序是YAML,它在某种程度上支持Ruby实现中的类型存储。您的散列类型为ActiveSupport::HashWithIndifferentAccess,所以当取回来时,ruby知道应该返回哪个对象(将其非序列化到HashWithIndifferentAccess)。
请注意,HashWithIndifferentAccess是一个散列,可以使用字符串或符号访问值,因此:
tmp = { foo: 'bar' }.with_indifferent_access
tmp[:foo] # => 'bar'
tmp['foo'] # => 'bar'使用普通散列(Hash.new),您可以得到:
tmp = { foo: 'bar' }
tmp[:foo] # => 'bar'
tmp['foo'] # => nil显然,在mysql中,散列存储为一个简单的字符串(YAML是带有约定的纯文本)。
https://stackoverflow.com/questions/31537883
复制相似问题