首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails 5.2应用程序记录的json序列化不正确

问rails 5.2应用程序记录的json序列化不正确
EN

Stack Overflow用户
提问于 2019-01-09 21:53:34
回答 2查看 2.1K关注 0票数 1

模型

代码语言:javascript
复制
class PushNotificationRequest < ApplicationRecord
  serialize :details

迁移

代码语言:javascript
复制
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

在控制台上创建数据

代码语言:javascript
复制
PushNotificationRequest.create(order: Spree::Order.last, details: {a: 2})

Mysql奇怪的存储

代码语言:javascript
复制
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

我是不是漏掉了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-09 23:10:37

根据docs 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
EN

Stack Overflow用户

发布于 2019-01-09 22:30:56

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

代码语言:javascript
复制
class PushNotificationRequest < ApplicationRecord
  serialize :details, JSON

顺便问一下,你确定MySQL能够存储JSON吗?(我只有PostgreSQL的经验)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54111737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档