rails 5.2 неправильная сериализация json для записи приложения - PullRequest
0 голосов
/ 09 января 2019

модель

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 ]

0 голосов
/ 09 января 2019

По документам 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 не требовалось и портило сериализацию. После удаления получил правильный json в mysql.

0 голосов
/ 09 января 2019

Я думаю, вам нужно определить, чтобы конкретно сериализовать атрибут как JSON в этом случае:

class PushNotificationRequest < ApplicationRecord
  serialize :details, JSON

Вы уверены, что MySQL может хранить JSON? (У меня есть опыт работы только с PostgreSQL)

...