diff options
author | Colin Kelley <colindkelley@gmail.com> | 2012-12-26 10:31:05 -0800 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2012-12-26 18:19:27 -0300 |
commit | d4c30a0226386f291bd8b1959fed12b3aca19164 (patch) | |
tree | 13633203d5f52c62dad47761708eed251508bfa7 /activemodel | |
parent | d9ce4fa7ac21dd3f623defa3cb1ac1a87b670ebe (diff) | |
download | rails-d4c30a0226386f291bd8b1959fed12b3aca19164.tar.gz rails-d4c30a0226386f291bd8b1959fed12b3aca19164.tar.bz2 rails-d4c30a0226386f291bd8b1959fed12b3aca19164.zip |
Tests and fix for validates_presence of :allow_nil, :allow_blank
Conflicts:
activemodel/lib/active_model/errors.rb
Diffstat (limited to 'activemodel')
-rw-r--r-- | activemodel/lib/active_model/errors.rb | 8 | ||||
-rw-r--r-- | activemodel/test/cases/validations/presence_validation_test.rb | 34 |
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 |