Skip to content

Commit 5ab94b2

Browse files
jzwlifo
authored andcommitted
validates_length_of with maximum should allow nil [#2309 status:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
1 parent c34d627 commit 5ab94b2

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

activemodel/lib/active_model/validations/length.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,10 @@ def validates_length_of(*attrs)
8080

8181
validates_each(attrs, options) do |record, attr, value|
8282
value = options[:tokenizer].call(value) if value.kind_of?(String)
83-
unless !value.nil? and value.size.method(validity_checks[option])[option_value]
84-
record.errors.add(attr, key, :default => custom_message, :count => option_value)
83+
unless option == :maximum and value.nil?
84+
unless !value.nil? and value.size.send(validity_checks[option], option_value)
85+
record.errors.add(attr, key, :default => custom_message, :count => option_value)
86+
end
8587
end
8688
end
8789
end

activemodel/test/cases/validations/length_validation_test.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,13 @@ def test_validates_length_of_using_minimum
5252
assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
5353
end
5454

55+
def test_validates_length_of_using_maximum_should_allow_nil
56+
Topic.validates_length_of :title, :maximum => 10
57+
t = Topic.create
58+
puts t.errors
59+
assert t.valid?
60+
end
61+
5562
def test_optionally_validates_length_of_using_minimum
5663
Topic.validates_length_of :title, :minimum => 5, :allow_nil => true
5764

@@ -75,9 +82,6 @@ def test_validates_length_of_using_maximum
7582

7683
t.title = ""
7784
assert t.valid?
78-
79-
t.title = nil
80-
assert !t.valid?
8185
end
8286

8387
def test_optionally_validates_length_of_using_maximum

0 commit comments

Comments
 (0)