diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb index a27ed97aca..9c56417d89 100644 --- a/activemodel/lib/active_model/validations/numericality.rb +++ b/activemodel/lib/active_model/validations/numericality.rb @@ -108,8 +108,8 @@ module ActiveModel end end - def read_attribute_for_validation(record, attr_name) - return super if record_attribute_changed_in_place?(record, attr_name) + def read_attribute_for_validation(record, attr_name, value) + return value if record_attribute_changed_in_place?(record, attr_name) came_from_user = :"#{attr_name}_came_from_user?" @@ -126,7 +126,7 @@ module ActiveModel end end - raw_value || super + raw_value || value end def record_attribute_changed_in_place?(record, attr_name) diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb index 4a77c7fe5f..9e2dee9a00 100644 --- a/activemodel/lib/active_model/validator.rb +++ b/activemodel/lib/active_model/validator.rb @@ -147,8 +147,9 @@ module ActiveModel # override +validate_each+ with validation logic. def validate(record) attributes.each do |attribute| - value = read_attribute_for_validation(record, attribute) + value = record.read_attribute_for_validation(attribute) next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) + value = read_attribute_for_validation(record, attribute, value) validate_each(record, attribute, value) end end @@ -166,8 +167,8 @@ module ActiveModel end private - def read_attribute_for_validation(record, attr_name) - record.read_attribute_for_validation(attr_name) + def read_attribute_for_validation(record, attr_name, value) + value end end diff --git a/activerecord/test/cases/validations/numericality_validation_test.rb b/activerecord/test/cases/validations/numericality_validation_test.rb index ffb8fd17b2..91cd6a0b0d 100644 --- a/activerecord/test/cases/validations/numericality_validation_test.rb +++ b/activerecord/test/cases/validations/numericality_validation_test.rb @@ -110,4 +110,12 @@ class NumericalityValidationTest < ActiveRecord::TestCase assert_not_predicate subject, :valid? end + + def test_allow_nil_works_for_casted_value + model_class.validates_numericality_of(:bank_balance, greater_than: 0, allow_nil: true) + + subject = model_class.new(bank_balance: "") + + assert_predicate subject, :valid? + end end