Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow_nil should work for casted value in NumericalityValidator #40765

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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