1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #40765 from kamipo/allow_nil_should_work_for_casted_value

`allow_nil` should work for casted value in `NumericalityValidator`
This commit is contained in:
Rafael França 2020-12-09 11:59:36 -05:00 committed by GitHub
commit 72dc9ac8e3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 6 deletions

View file

@ -108,8 +108,8 @@ module ActiveModel
end end
end end
def read_attribute_for_validation(record, attr_name) def read_attribute_for_validation(record, attr_name, value)
return super if record_attribute_changed_in_place?(record, attr_name) return value if record_attribute_changed_in_place?(record, attr_name)
came_from_user = :"#{attr_name}_came_from_user?" came_from_user = :"#{attr_name}_came_from_user?"
@ -126,7 +126,7 @@ module ActiveModel
end end
end end
raw_value || super raw_value || value
end end
def record_attribute_changed_in_place?(record, attr_name) def record_attribute_changed_in_place?(record, attr_name)

View file

@ -147,8 +147,9 @@ module ActiveModel
# override +validate_each+ with validation logic. # override +validate_each+ with validation logic.
def validate(record) def validate(record)
attributes.each do |attribute| 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]) 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) validate_each(record, attribute, value)
end end
end end
@ -166,8 +167,8 @@ module ActiveModel
end end
private private
def read_attribute_for_validation(record, attr_name) def read_attribute_for_validation(record, attr_name, value)
record.read_attribute_for_validation(attr_name) value
end end
end end

View file

@ -110,4 +110,12 @@ class NumericalityValidationTest < ActiveRecord::TestCase
assert_not_predicate subject, :valid? assert_not_predicate subject, :valid?
end 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 end