ActiveRecord serialize: false or 0 serialized to NULL in database

Hi there!

I create some STI models with custom serialize like this:

class Property < ApplicationRecord
end
class StringProperty < Property
end
class BooleanProperty < Property
  class BooleanSerializer
    def self.dump(value)
      value.to_s
    end

    def self.load(value)
      value.eql? 'true'
    end
  end

  serialize :value, BooleanSerializer
end
class IntegerProperty < Property
  class IntegerSerializer
    def self.dump(value)
      value.to_s
    end

    def self.load(value)
      value.to_i
    end
  end

  serialize :value, IntegerSerializer
end

The problem comes when i.e. a BooleanProperty.create name: 'Are you a senior developer?', value: false it’s persisted value column like NULL. And same with IntergerProperty and 0 value.

And this it’s really weird, when I run StringProperty.create name: 'FooBar', value: 'false' it’s properly persisted.

It’s me or a bug?

P.S: My apologies for my noob english.

@javier.valencia what is the type of the column value in your migration?

In my migration file it’s a String type nulls allowed.

I have a new friend: ActiveRecord::Attributes::ClassMethods

Good that you found the attribute method. It is more suitable for the use case.

Actually, internally, the serialize method calls the attribute method only.

Your code in the original post works with “truthy” values. If you use true instead of false and any other digit except 0 then it works. I think somewhere in the casting it is messing with the values.