From 4c96d02259bbddb24d1e04fe54d6beb441e5d5af Mon Sep 17 00:00:00 2001 From: Eric Anderson Date: Fri, 6 Apr 2012 17:59:32 -0400 Subject: [PATCH] More intuitive support for making Boolean's required. 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] --- lib/mongo_mapper/plugins/keys.rb | 6 +++++- test/unit/test_validations.rb | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/mongo_mapper/plugins/keys.rb b/lib/mongo_mapper/plugins/keys.rb index 006a6477e..085a3e9b0 100644 --- a/lib/mongo_mapper/plugins/keys.rb +++ b/lib/mongo_mapper/plugins/keys.rb @@ -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] diff --git a/test/unit/test_validations.rb b/test/unit/test_validations.rb index 5756ac8c4..0d8881502 100644 --- a/test/unit/test_validations.rb +++ b/test/unit/test_validations.rb @@ -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