From b0c66a2f92eaed20890164f8f90b466c4e140645 Mon Sep 17 00:00:00 2001 From: Matthew Draper Date: Sun, 28 May 2017 11:00:07 +0930 Subject: [PATCH] Merge pull request #29249 from bradleypriest/numericality-precision-regression Fix regression in Numericality validator --- activemodel/CHANGELOG.md | 6 ++++++ .../lib/active_model/validations/numericality.rb | 4 +++- activerecord/test/cases/validations_test.rb | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md index 1a48533842..cd747587a5 100644 --- a/activemodel/CHANGELOG.md +++ b/activemodel/CHANGELOG.md @@ -1,3 +1,9 @@ +* Fix regression in numericality validator when comparing Decimal and Float input + values with more scale than the schema. + + *Bradley Priest* + + ## Rails 5.0.3 (May 12, 2017) ## * The original string assigned to a model attribute is no longer incorrectly diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb index 095590b44c..4f1c1143c2 100644 --- a/activemodel/lib/active_model/validations/numericality.rb +++ b/activemodel/lib/active_model/validations/numericality.rb @@ -39,7 +39,9 @@ module ActiveModel return end - unless raw_value.is_a?(Numeric) + if raw_value.is_a?(Numeric) + value = raw_value + else value = parse_raw_value_as_a_number(raw_value) end diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index 85e33d2218..1c51b247f3 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -169,6 +169,20 @@ class ValidationsTest < ActiveRecord::TestCase Topic.reset_column_information end + def test_numericality_validation_checks_against_raw_value + klass = Class.new(Topic) do + def self.model_name + ActiveModel::Name.new(self, nil, "Topic") + end + attribute :wibble, :decimal, scale: 2, precision: 9 + validates_numericality_of :wibble, greater_than_or_equal_to: BigDecimal.new("97.18") + end + + assert_not klass.new(wibble: "97.179").valid? + assert_not klass.new(wibble: 97.179).valid? + assert_not klass.new(wibble: BigDecimal.new("97.179")).valid? + end + def test_acceptance_validator_doesnt_require_db_connection klass = Class.new(ActiveRecord::Base) do self.table_name = 'posts'