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:
commit
72dc9ac8e3
3 changed files with 15 additions and 6 deletions
|
@ -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)
|
||||||
|
|
|
@ -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
|
||||||
|
|
||||||
|
|
|
@ -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
|
||||||
|
|
Loading…
Reference in a new issue