Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql ruby/hash:ActiveSupport::HashWithInferenceTaccess_Mysql_Ruby On Rails_Ruby - Fatal编程技术网

Mysql ruby/hash:ActiveSupport::HashWithInferenceTaccess

Mysql ruby/hash:ActiveSupport::HashWithInferenceTaccess,mysql,ruby-on-rails,ruby,Mysql,Ruby On Rails,Ruby,我将散列存储到mysql,但结果让我感到困惑: 散列: 我在模型中使用了序列化 serialize :title mysql中的结果如下: --- !ruby/hash:ActiveSupport::HashWithIndifferentAccess all: test en: test 谁能告诉我这是什么意思?为什么mysql中有一个ruby/hash:ActiveSupport::HashWithIndifferentAccess?哈希需要序列化,默认序列化程序是YAML,它在ruby实

我将散列存储到mysql,但结果让我感到困惑:

散列:

我在模型中使用了序列化

serialize :title
mysql中的结果如下:

--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
all: test
en: test

谁能告诉我这是什么意思?为什么mysql中有一个
ruby/hash:ActiveSupport::HashWithIndifferentAccess

哈希需要序列化,默认序列化程序是YAML,它在ruby实现中以某种方式支持类型的存储。您的散列类型为ActiveSupport::HashWithInferenceTaccess,因此在回迁时,ruby知道应该回迁哪个对象(将其取消序列化为HashWithInferenceTaccess)

请注意,HashWithInferenceTaccess是一个可以使用字符串或符号访问值的哈希,因此:

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是带有约定的纯文本)

TL;医生:

serialize :title, Hash
这里发生的事情是,
serialize
内部将yaml转储类实例。rails中的散列是蒙基补丁,以使may具有不受影响的访问权限。后者意味着您可以自由使用字符串和相应的符号作为键:

h = { 'a' => 42 }.with_indifferent_access
puts h[:a]
#⇒ 42

Sidenote
:要将json存储为json,应该使用PostgreSQL,而不是MySQL RDBMS。
h = { 'a' => 42 }.with_indifferent_access
puts h[:a]
#⇒ 42