Skip to content

Commit

Permalink
More intuitive support for making Boolean's required.
Browse files Browse the repository at this point in the history
validates_presence_of :field doesn't work for a Boolean field because false
is considered blank. Instead you have to use
validates_inclusions_of :field, :in => [true, false]. This is a known annoyance
of AR. We can make this better in MongoMapper by having the :required shortcut
do the right thing. So if you do:

    key :field, String, :required => true

Then it does a validates_presence_of :field. But if you do:

    key :flag, Boolean, :required => true

It does a validates_inclusion_of :field, :in => [true, false]
  • Loading branch information
eric1234 committed Apr 6, 2012
1 parent 41cd0b1 commit 4c96d02
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/mongo_mapper/plugins/keys.rb
Expand Up @@ -121,7 +121,11 @@ def create_validations_for(key)
attribute = key.name.to_sym

if key.options[:required]
validates_presence_of(attribute)
if key.type == Boolean
validates_inclusion_of attribute, :in => [true, false]
else
validates_presence_of(attribute)
end
end

if key.options[:unique]
Expand Down
13 changes: 13 additions & 0 deletions test/unit/test_validations.rb
Expand Up @@ -245,6 +245,19 @@ class ValidationsTest < Test::Unit::TestCase
doc.should_not have_error_on(:action)
end

should "work with :required shortcut on Boolean type" do
@document.key :flag, Boolean, :required => true

doc = @document.new
doc.should have_error_on(:flag, 'is not included in the list')

doc.flag = true
doc.should_not have_error_on(:action)

doc.flag = false
doc.should_not have_error_on(:action)
end

should "not have error if allow nil is true and value is nil" do
@document.key :action, String
@document.validates_inclusion_of :action, :in => %w(kick run), :allow_nil => true
Expand Down

0 comments on commit 4c96d02

Please sign in to comment.