我们在应用程序中使用money-rails
gem。到现在为止,我们可以使用4位十进制数字精度,但是我们需要切换到6位。不幸的是,我无法将精度更高的数字存储到Postgres中-数字在保存之前四舍五入。
class MyModel < ApplicationRecord
monetize :price_cents # :price_cents, :decimal, default: 0, precision: 30, scale: 10
end
金钱本身似乎可以以更高的精度工作正常
pry(main)> Money.new(181.123456789).to_f
=> 1.81123456789
在控制台中测试模型。保存前一切正常。
my_model = MyModel.find(1)
my_model.price = Money.new(181.123456789)
my_model.price.to_f # => 1.81123456789
my_model.save
my_model.price.to_f # => 1.8112
并且ActiveRecord输出说修剪后的号码实际上正在发送到数据库。 (请注意181.12)。
UPDATE "my_models" SET "price_cents" = $1 ... [["price_cents", "181.12"] ...]
是否有任何方法可以使money-rails
宝石更精确地工作?似乎Money gem本身没有更高的精度问题。
该行为来自四舍五入,将其关闭,请使用:
Money.infinite_precision = true
这里是测试:
require "bundler/inline"
gemfile(ENV['INSTALL']=='1') do
source "https://rubygems.org"
gem "rails", '~>6.0'
gem "sqlite3"
gem 'money-rails'
end
require "minitest/autorun"
require "logger"
require "active_record"
require 'money-rails'
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table(:models, force: true){|t| t.decimal :price_cents, default: 0, precision: 30, scale: 10 }
end
# to remove config warnings:
Money.locale_backend = :currency
Money.default_currency= :usd
# actual fix:
Money.infinite_precision = true
MoneyRails::Hooks.init # in a normal app is called automatically
class Model < ActiveRecord::Base
monetize :price_cents
end
class BugTest < Minitest::Test
def test_association_stuff
m = Model.create!(price_cents: 181.123456789).reload
assert_equal 181.123456789, m.price_cents
assert_equal 1.81123456789, m.price.to_f
m2 = Model.create(price: Money.new(182.123456789)).reload
assert_equal 1.82123456789, m2.price.to_f
end
end