aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activemodel/lib/active_model/errors.rb8
-rw-r--r--activemodel/test/cases/validations/presence_validation_test.rb34
2 files changed, 41 insertions, 1 deletions
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 963e52bff3..92c2512aa4 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -322,9 +322,15 @@ module ActiveModel
# person.errors.messages
# # => {:name=>["can't be blank"]}
def add_on_blank(attributes, options = {})
+ return if options[:allow_blank]
+
Array(attributes).each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
- add(attribute, :blank, options) if value.blank?
+ if value.nil?
+ add(attribute, :blank, options) unless options[:allow_nil]
+ elsif value.blank?
+ add(attribute, :blank, options)
+ end
end
end
diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb
index 510c13a7c3..fe2ee7b409 100644
--- a/activemodel/test/cases/validations/presence_validation_test.rb
+++ b/activemodel/test/cases/validations/presence_validation_test.rb
@@ -70,4 +70,38 @@ class PresenceValidationTest < ActiveModel::TestCase
p[:karma] = "Cold"
assert p.valid?
end
+
+ def test_allow_nil
+ Topic.validates_presence_of(:title, :allow_nil => true)
+
+ t = Topic.new(:title => "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = " "
+ assert t.invalid?, t.errors.full_messages
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
+
+ def test_allow_blank
+ Topic.validates_presence_of(:title, :allow_blank => true)
+
+ t = Topic.new(:title => "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.valid?, t.errors.full_messages
+
+ t.title = " "
+ assert t.valid?, t.errors.full_messages
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
end