Boolean field validation in Rails ActiveRecord

I need to check boolean fields for a Rails ActiveRecord object. I used a generic solution to this problem:

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

      

But while these solutions fix the value validation issue false

, it still allows strings to be stored in boolean_field

:

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

      

Why does this happen if I have indicated inclusion in [true, false]

? And more importantly, how to check valid and false values only ?

PS If it matters to the question, I am using PostgreSQL.

+3


source to share


1 answer


You can check by checking the data type, you can use is_a?

and pass the data type class name 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 boolean



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

      

Add custom validation with this logic

validate :check_boolean_field

def check_boolean_field
  errors.add(...) unless boolean_field.is_a?(Boolean)
end

      

+5


source







All Articles