代码之家  ›  专栏  ›  技术社区  ›  t0il3ts0ap

Rails 5.2应用程序记录的JSON序列化不正确

  •  0
  • t0il3ts0ap  · 技术社区  · 6 年前

    模型

    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 我使用的是MySQL8.0.12和Rails 5.12

    我有什么东西不见了吗?

    2 回复  |  直到 6 年前
        1
  •  0
  •   bo-oz    6 年前

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

    class PushNotificationRequest < ApplicationRecord
      serialize :details, JSON
    

    你确定mysql可以存储json吗?(我只对PostgreSQL有经验)

        2
  •  0
  •   t0il3ts0ap    6 年前

    根据文件 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。