ActiveRecord序列化发送nil到当前属性的自定义序列化程序

问题描述:

我有以下自定义序列化器:

I have the following custom serializer:

class ReportCardDataSerializer
  def self.dump(hash)
    hash.to_json
  end

  def self.load(json)
    # json.class == NilClass, why????
    hash = (json || {}).with_indifferent_access
  end
end

以及以下具有序列化 data 属性且数据库列设置为NOT NULL的类。

And the following class with a serialized data attribute with database column set to NOT NULL.

class ReportCardGroup < ActiveRecord::Base
  serialize :data, ReportCardDataSerializer # data is PostgreSQL jsonb column
end

ReportCardDataSerializer 转储方法可以正常工作。但是,在尝试 load ReportCardDataSerializer load 方法时,即使数据库列不是nil,也会发送nil。

The ReportCardDataSerializer dump method works as expected. But on trying to load ReportCardDataSerializer load method gets sent nil even though the database column is not nil.

为什么会这样?

我通过查看ActiveRecord来弄清楚了

I figured it out by going through the ActiveRecord serialization class.

ActiveRecord序列化程序调用 type_cast_from_database

ActiveRecord serializer calls type_cast_from_database:

def type_cast_from_database(value)
    if default_value?(value)
      value
    else
      coder.load(super)
    end
end

def default_value?(value)
    value == coder.load(nil) # HERE: Calls Serializer with nil
end

我认为ReportCardDataSerializer永远不必处理nil,但ActiveRecord实际上首先尝试加载nil以测试默认值。

I assumed ReportCardDataSerializer would never have to process nil, but ActiveRecord actually first tries loading nil to test for the default value.