0

I have a tableless class defined like this:

class MyClass
  class MyClassRules < ActiveRecord::Base
    column :a, :integer
    column :b, :boolean
    column :c, :datetime
    column :d, :decimal, :precision => 10, :scale => 4
    column :e, :string
  end
end

The object of type MyClassRules gets automatically built when I instantiate an object of type MyClass, and it is stored serialized in a single column in the my_class table called rules and accessible from my_obj.rules. So I can also make calls like my_obj.rules.a.

The issue I'm having is the default value of the decimal column. Without providing values when I build the object, I would expect all values to default to nil. Instead, what I get is this:

#<MyClass::MyClassRules
  a: nil,
  b: nil,
  c: nil,
  d: #<BigDecimal:7fce8f295620,'0.0',9(9)>,
  e: nil
>

Indeed, most of them default to nil, but decimal defaults to 0.0. I've even tried passing a :default => nil param to the declaration, and that does nothing.

How can I force a decimal column to default to nil?

kid_drew
  • 3,857
  • 6
  • 28
  • 38

1 Answers1

1

I'm answering my own question. Modifying the class to initialize the values to nil works:

class MyClass
  class MyClassRules < ActiveRecord::Base
    after_initialize :init

    column :a, :integer
    column :b, :boolean
    column :c, :datetime
    column :d, :decimal, :precision => 10, :scale => 4
    column :e, :string

    def init
      self.d = nil
    end
  end
end

Seems unnecessary, but it gets the job done.

kid_drew
  • 3,857
  • 6
  • 28
  • 38