rails 4.2 中的 ActiveRecord 存储属性在序列化时中断

ActiveRecord store attribute in rails 4.2 breaking on serialization

我正在将 Rails 3 项目升级到 Rails 4,它在我使用 ActiveRecord Store 属性 的模型中出现故障。我的模型如下所示:

class ModelClass < ActiveRecord::Base
    attr_accessible :attr_1, ..., attr_n, as: :admin

    store :properties, accessors: [:attr_1, ..., :attr_n], coder: JSON
end

:properties 字段是 Postgres 中的文本字段。

当我尝试访问此模型中的数据时,我得到以下信息 JSON::ParserError:

795: unexpected token at '{"attr_1"=>"", ..., "attr_n"=>""}'

这些记录都是在Rails3中创建的,在升级到Rails4之前我的模型class没有coder: JSON结尾的store 呼叫。看起来数据库中的数据没有被正确序列化有没有人知道为什么以及如何修复它?是因为我的数据看起来像数据库中的 ruby 散列和 => 散列火箭吗?

是的,JSON 解析器失败,因为字符串不是 json。

您可以通过评估字符串并将其转换为 json 来修复您的记录。 eval 应谨慎使用,但如果这是一次性工作,那么您可能 运行 在 rails console 中使用类似的东西。

ModelClass.all.each do |m|
  m.properties = eval(m.properties).to_json
  m.save
end

未测试,请在更新整个 table 之前尝试一条记录。