【问题标题】:rails 5.2 improper json serialization for application recordrails 5.2 应用程序记录的不正确 json 序列化
【发布时间】:2019-01-09 13:53:34
【问题描述】:

型号

class PushNotificationRequest < ApplicationRecord
  serialize :details
移民
class CreateNotificationRequests < ActiveRecord::Migration[5.2]
  def change
    create_table :notification_requests do |t|
      t.references :order, references: :spree_orders, index: false
      t.string :key                             
      t.json :details                           
      t.string :type
      t.timestamps
    end
  end
end

在控制台上创建数据

PushNotificationRequest.create(order: Spree::Order.last, details: {a: 2})

Mysql怪异存储

mysql> select * from notification_requests;
+----+----------+------+----------------+-------------------------+-----------+---------------------+---------------------+
| id | order_id | key  | details        | type                    | status    | created_at          | updated_at          |
+----+----------+------+----------------+-------------------------+-----------+---------------------+---------------------+
|  7 |       19 | NULL | "---\n:a: 2\n" | PushNotificationRequest | INITIATED | 2019-01-09 13:45:40 | 2019-01-09 13:45:40 |
+----+----------+------+----------------+-------------------------+-----------+---------------------+---------------------+

details 列存储为一些奇怪的字符串,而不是正确的 json 我正在使用 mysql 8.0.12 和 rails 5.12

我有什么遗漏吗?

【问题讨论】:

    标签: mysql ruby-on-rails json-serialization


    【解决方案1】:

    根据文档Keep in mind that database adapters handle certain serialization tasks for you. For instance: json and jsonb types in PostgreSQL will be converted between JSON object/array syntax and Ruby Hash or Array objects transparently. There is no need to use serialize in this case.

    serialize :details 不是必需的,它在某种程度上破坏了序列化。删除后,在mysql中得到了正确的json。

    【讨论】:

      【解决方案2】:

      我认为在这种情况下您需要定义专门将属性序列化为 JSON:

      class PushNotificationRequest < ApplicationRecord
        serialize :details, JSON
      

      你确定MySQL能够顺便存储JSON吗? (我只对 PostgreSQL 有经验)

      【讨论】:

      • 我之前尝试过。它给了ActiveRecord::AttributeMethods::Serialization::ColumnNotSerializableError: Column `details` of type ActiveRecord::Type::Json does not support `serialize` feature. Usually it means that you are trying to use `serialize` on a column that already implements serialization natively.
      • Ya mysql 从 5.7 开始支持 json
      • 奇怪,在文档中:api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/…。当 yopu 检索记录时会发生什么,虽然它在数据库中有一个奇怪的值,但可能是 Rails 能够正确检索它作为 JSON 对象。]
      • 哦,文档中说你根本不需要serialize,如果列是json。它有效,感谢您的文档
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多