3

I need to validate boolean fields for a Rails ActiveRecord object. I used the common solution to this problem:

validates :boolean_field, :inclusion => { :in => [true, false] }

But although this solutions solves the problem with validating false values, it still allows to save strings to the boolean_field:

my_object.boolean_field = "string"
my_object.save # => true
my_object.boolean_field # => false

Why does this happen if I specified the inclusion to [true, false]? And more importantly, how do I validate only true and false values?

P.S. If it is important to the question, I'm using PostgreSQL.

Sergey
  • 47,222
  • 25
  • 87
  • 129
  • 1
    Look at here http://stackoverflow.com/questions/5170008/rails-validating-inclusion-of-a-boolean-fails-tests might help you – Dipak Gupta Oct 14 '14 at 14:28

1 Answers1

6

You can validate by checking datatype, you can use is_a? and pass class name of the datatype as a parameter

pry(main)> a = "aaaaa"
=> "aaaaa"
pry(main)> a.is_a?(Boolean)
=> false

Since it was a string it returned false, now try for boolean

pry(main)> b = true
=> true
pry(main)> b.is_a?(Boolean)
=> true

Add a custom validation by using this logic

validate :check_boolean_field

def check_boolean_field
  errors.add(...) unless boolean_field.is_a?(Boolean)
end
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78