ActiveRecord serialize sending nil to custom serializer for present attribute

柔情痞子 提交于 2020-01-14 13:43:23

问题


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

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

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.

Why is this happening?


回答1:


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

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

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



来源:https://stackoverflow.com/questions/37228752/activerecord-serialize-sending-nil-to-custom-serializer-for-present-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!