Skip to content

Commit

Permalink
Merge pull request #40765 from kamipo/allow_nil_should_work_for_caste…
Browse files Browse the repository at this point in the history
…d_value

`allow_nil` should work for casted value in `NumericalityValidator`
  • Loading branch information
rafaelfranca committed Dec 9, 2020
1 parent eedd636 commit fe8db70
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
6 changes: 3 additions & 3 deletions activemodel/lib/active_model/validations/numericality.rb
Expand Up @@ -108,8 +108,8 @@ def allow_only_integer?(record)
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?"

Expand All @@ -126,7 +126,7 @@ def read_attribute_for_validation(record, attr_name)
end
end

raw_value || super
raw_value || value
end

def record_attribute_changed_in_place?(record, attr_name)
Expand Down
7 changes: 4 additions & 3 deletions activemodel/lib/active_model/validator.rb
Expand Up @@ -147,8 +147,9 @@ def initialize(options)
# 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
Expand All @@ -166,8 +167,8 @@ def check_validity!
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

Expand Down
Expand Up @@ -110,4 +110,12 @@ def test_aliased_attribute

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

0 comments on commit fe8db70

Please sign in to comment.