从 3.2 升级到 Rails 4.0 时商店停止工作
Store stops working when upgrading to Rails 4.0 from 3.2
我正在将我的 Rails 应用程序从 v3.2 升级到 v4.0。在我的 User
模型中,我有一个 JSON 编码商店:
store :settings, accessors: [
:confirmed,
:receive_marketing_emails,
:receive_reply_emails
], coder: JSON
这按预期工作,序列化 User.settings
并提供访问器。
然而,当我移动到 Rails 4.0 时,商店停止工作。当我尝试查找任何用户时出现以下错误:
JSON::ParserError: 795: unexpected token at '---
:confirmed,
:receive_marketing_emails,
:receive_reply_emails
'
任何人都可以提供任何见解吗?
Rails Upgrade Guide中有这样的语句:
Rails 4.0 has changed ActiveModel::Serializers::JSON.include_root_in_json default value to false. Now, Active Model Serializers and Active Record objects have the same default behavior.
我建议当您访问 User
实例时,json 字段不能反序列化,因为它不需要根,而序列化数据有它。
要恢复 Rails 3.2 行为,请将其放入您的 config/initializers/wrap_parameters.rb
:
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = true
end
根据 this question's answer:
Earlier (ActiveRecord 3.2.8) the data is stored in database is in YAML format, and it was working with "coder: JSON", which is not case in ActiveRecord 4.2.4.
因此,即使您指定 coder: JSON
,数据也被序列化为 YAML,而不是 JSON。奇怪。
为了回答我自己的问题,在 Rails 4.0 中我只需要将 coder: JSON
更改为 coder: YAML
。
我正在将我的 Rails 应用程序从 v3.2 升级到 v4.0。在我的 User
模型中,我有一个 JSON 编码商店:
store :settings, accessors: [
:confirmed,
:receive_marketing_emails,
:receive_reply_emails
], coder: JSON
这按预期工作,序列化 User.settings
并提供访问器。
然而,当我移动到 Rails 4.0 时,商店停止工作。当我尝试查找任何用户时出现以下错误:
JSON::ParserError: 795: unexpected token at '---
:confirmed,
:receive_marketing_emails,
:receive_reply_emails
'
任何人都可以提供任何见解吗?
Rails Upgrade Guide中有这样的语句:
Rails 4.0 has changed ActiveModel::Serializers::JSON.include_root_in_json default value to false. Now, Active Model Serializers and Active Record objects have the same default behavior.
我建议当您访问 User
实例时,json 字段不能反序列化,因为它不需要根,而序列化数据有它。
要恢复 Rails 3.2 行为,请将其放入您的 config/initializers/wrap_parameters.rb
:
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = true
end
根据 this question's answer:
Earlier (ActiveRecord 3.2.8) the data is stored in database is in YAML format, and it was working with "coder: JSON", which is not case in ActiveRecord 4.2.4.
因此,即使您指定 coder: JSON
,数据也被序列化为 YAML,而不是 JSON。奇怪。
为了回答我自己的问题,在 Rails 4.0 中我只需要将 coder: JSON
更改为 coder: YAML
。