模型
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
有什么我不知道的吗?
2条答案
按热度按时间x8goxv8g1#
根据文件
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。t1rydlwq2#
在这种情况下,我认为您需要定义将属性具体序列化为json:
顺便问一下,你确定mysql能够存储json吗(我只对postgresql有经验)