ActiveRecord column decimal default value

耗尽温柔 提交于 2019-12-25 03:57:20

问题


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?


回答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.



来源:https://stackoverflow.com/questions/24123285/activerecord-column-decimal-default-value

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