本文介绍了ActiveRecord列的十进制默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的无表类:

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

实例化 MyClass 类型的对象时,会自动构建 MyClassRules 类型的对象,并将其序列化存储在 my_class 表称为 rules ,可从 my_obj.rules 访问.因此,我也可以拨打 my_obj.rules.a .

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.

我遇到的问题是小数列的默认值.在构建对象时不提供值,我希望所有值默认为nil.相反,我得到的是这样:

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
>

实际上,它们大多数默认为nil,但十进制默认为 0.0 .我什至尝试传递:default =>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.

如何强制将小数列默认设置为nil?

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

推荐答案

我正在回答自己的问题.修改类以将值初始化为nil即可:

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.

这篇关于ActiveRecord列的十进制默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:55
查看更多