Ruby on rails 如果通过关联访问,为什么BigDecimal刻度会发生变化?

Ruby on rails 如果通过关联访问,为什么BigDecimal刻度会发生变化?,ruby-on-rails,ruby,bigdecimal,Ruby On Rails,Ruby,Bigdecimal,我有两个RubyonRails模型Farm和Harvest。农场属于收获。以下是模型: class Farm < ActiveRecord::Base acts_as_singleton belongs_to :harvest validates :harvest, presence: true, allow_blank: true serialize :harvest_time, Tod::TimeOfDay validates :harvest_time, pres

我有两个RubyonRails模型
Farm
Harvest
。农场属于收获。以下是模型:

class Farm < ActiveRecord::Base
  acts_as_singleton
  belongs_to :harvest
  validates :harvest, presence: true, allow_blank: true
  serialize :harvest_time, Tod::TimeOfDay
  validates :harvest_time, presence: true, allow_blank: true
  validates :hash_rate, presence: true
  validates_with HashRateValidator
end

class Harvest < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true
  validates :date, presence: true
  validates :amount, presence: true
  validates :identifier, presence: true
  validates :amount, numericality: { :greater_than => 0 }
end
奇怪的是,分配给农场的收获量和收获量的值在此之后不匹配:

(byebug) Farm.instance.harvest.amount
435.435

(byebug) @harvest.amount
435.435345343

(byebug) Farm.instance.harvest.id
12

(byebug) @harvest.id
12
数量小数被设置为刻度为8,精度为6(从迁移开始),下面是schema.rb文件的相关部分:

create_table "harvests", force: :cascade do |t|
    t.datetime "date"
    t.decimal  "amount",                          precision: 6, scale: 8
    t.integer  "identifier"
    t.datetime "created_at",                                                              null: false
    t.datetime "updated_at",                                                              null: false
    ...
  end

那么,这是怎么回事?金额应该是完全相同的值

我明白了。规模和精度没有意义。精度是BigDecimal amount上的数字量,scale是小数点右侧出现的数字量。由于精度设置为6,小数点后的8位数字无法显示刻度。因此,当数字来自数据库时,它被截断,当它来自内存时,它的所有数字都在小数点之后我通过将精度设置为18并将比例设置为8来修复它,这意味着总共有18位数字,其中8位出现在小数点右侧。

Sqlite允许非相干精度=>6和比例=>8。博士后没有

create_table "harvests", force: :cascade do |t|
    t.datetime "date"
    t.decimal  "amount",                          precision: 6, scale: 8
    t.integer  "identifier"
    t.datetime "created_at",                                                              null: false
    t.datetime "updated_at",                                                              null: false
    ...
  end