Search code examples
mysqlruby-on-railsjson-serialization

rails 5.2 improper json serialization for application record


model

class PushNotificationRequest < ApplicationRecord
  serialize :details
migration
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

Data creation on console

PushNotificationRequest.create(order: Spree::Order.last, details: {a: 2})

Mysql weird storage

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 |
+----+----------+------+----------------+-------------------------+-----------+---------------------+---------------------+

The details column is stored as some weird string and not a proper json I am using mysql 8.0.12 and rails 5.12

Is there something I am missing?


Solution

  • According to the 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.

    Therefore, serialize :details was not required in the model and was corrupting the serialization in a way. After removing, got the correct json in mysql.