1

模型

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

有什么我想念的吗?

4

2 回答 2

2

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

于 2019-01-09T15:10:36.713 回答
0

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

class PushNotificationRequest < ApplicationRecord
  serialize :details, JSON

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

于 2019-01-09T14:30:55.677 回答