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

Viewed 56142

Does rails have a validator like validates_numericality_of for boolean or do I need to roll my own?

5 Answers

Since Rails 3, you can do:

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

You can use the shorter version:

validates :field, inclusion: [true, false]

Extra thought. When dealing with enums, I like to use a constant too:

KINDS = %w(opening appointment).freeze

enum kind: KINDS

validates :kind, inclusion: KINDS

Answer according to Rails Docs 5.2.3

This helper (presence) validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.

Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:

validates :boolean_field_name, inclusion: { in: [true, false] }
Related