aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorSean Griffin <sean@thoughtbot.com>2014-12-22 07:07:42 -0700
committerSean Griffin <sean@thoughtbot.com>2014-12-22 07:08:31 -0700
commit41f1323e74c348b5fdcbb55b30ecf349c0cad509 (patch)
tree83410dcb73d0c9ef3a4c54f19a01b151276324ed /activerecord
parentd610cd0ff82353e36f68f14fe6fecee11d51ad09 (diff)
downloadrails-41f1323e74c348b5fdcbb55b30ecf349c0cad509.tar.gz
rails-41f1323e74c348b5fdcbb55b30ecf349c0cad509.tar.bz2
rails-41f1323e74c348b5fdcbb55b30ecf349c0cad509.zip
Correctly handle Float -> BigDecimal with unspecified precision
Fixes #18122
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/type/decimal.rb10
-rw-r--r--activerecord/test/cases/type/decimal_test.rb5
2 files changed, 14 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/type/decimal.rb b/activerecord/lib/active_record/type/decimal.rb
index d10778eeb6..7b2bee2c42 100644
--- a/activerecord/lib/active_record/type/decimal.rb
+++ b/activerecord/lib/active_record/type/decimal.rb
@@ -16,7 +16,7 @@ module ActiveRecord
def cast_value(value)
case value
when ::Float
- BigDecimal(value, float_precision)
+ convert_float_to_big_decimal(value)
when ::Numeric, ::String
BigDecimal(value, precision.to_i)
else
@@ -28,6 +28,14 @@ module ActiveRecord
end
end
+ def convert_float_to_big_decimal(value)
+ if precision
+ BigDecimal(value, float_precision)
+ else
+ value.to_d
+ end
+ end
+
def float_precision
if precision.to_i > ::Float::DIG + 1
::Float::DIG + 1
diff --git a/activerecord/test/cases/type/decimal_test.rb b/activerecord/test/cases/type/decimal_test.rb
index da30de373e..c028aa52af 100644
--- a/activerecord/test/cases/type/decimal_test.rb
+++ b/activerecord/test/cases/type/decimal_test.rb
@@ -15,6 +15,11 @@ module ActiveRecord
assert_equal BigDecimal.new("123.0"), type.type_cast_from_user(123.0)
end
+ def test_type_cast_from_float_with_unspecified_precision
+ type = Decimal.new
+ assert_equal 22.68.to_d, type.type_cast_from_user(22.68)
+ end
+
def test_type_cast_decimal_from_rational_with_precision
type = Decimal.new(precision: 2)
assert_equal BigDecimal("0.33"), type.type_cast_from_user(Rational(1, 3))