Rails: how do I validate that something is a boolean? Rails: how do I validate that something is a boolean? ruby-on-rails ruby-on-rails

Rails: how do I validate that something is a boolean?


Since Rails 3, you can do:

validates :field, inclusion: { in: [ true, false ] }


I believe for a boolean field you will need to do something like:

validates_inclusion_of :field_name, :in => [true, false]

From an older version of the API: "This is due to the way Object#blank? handles boolean values. false.blank? # => true"

I'm not sure if this will still be fine for Rails 3 though, hope that helped!


When I apply this, I get:

Warning from shoulda-matchers:

You are using validate_inclusion_of to assert that a boolean columnallows boolean values and disallows non-boolean ones. Be aware that itis not possible to fully test this, as boolean columns willautomatically convert non-boolean values to boolean ones. Hence, youshould consider removing this test.