我有两个Rails模型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只有一个农场(由于作为单身宝石的行为而得以完成)。每次收获时,农庄的收获关联都会发生变化,因为它总是指向最近的收获。由于我使用的是“农场”作为单例模型,所以我使用以下代码更新“农场”:
@harvest = Harvest.new(
:date => DateTime.now,
:amount => amount,
:identifier => new_identifier,
:user => current_user,
:assigned => false
)
if @harvest.save
Farm.instance.update_attributes(:harvest => @harvest)
byebug奇怪的是,收获量的值与分配给农场的收获量不匹配:
(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这是怎么回事?金额应该是完全相同的价值!
发布于 2016-02-15 21:14:58
我想通了。规模和精确度是没有意义的。精度是BigDecimal数量上的数字数量,标度是显示在小数点右侧的数字的数量。由于精度设置为6,小数点后刻度不能容纳8位数字。因此,当数字来自数据库时,它被截断,当它来自内存时,它的所有数字都在小数点之后。I将精度设置为18,小数位数设置为8,这意味着总共18位数字和小数点右边的8位数字。
Sqlite允许非相干精度的=> 6和比例尺=> 8,Postgres没有。
https://stackoverflow.com/questions/35415006
复制相似问题