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

Ruby on-RailsValidation

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Since Rails 3, you can do:

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

Solution 2 - Ruby on-Rails

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 http://www.railsbrain.com/api/rails-2.2.2/doc/index.html?a=M001821&name=validates_presence_of">API</a>;: "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!

Solution 3 - Ruby on-Rails

When I apply this, I get:

Warning from shoulda-matchers:

You are using validate_inclusion_of to assert that a boolean column allows boolean values and disallows non-boolean ones. Be aware that it is not possible to fully test this, as boolean columns will automatically convert non-boolean values to boolean ones. Hence, you should consider removing this test.

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

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] }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaaronaView Question on Stackoverflow
Solution 1 - Ruby on-RailsDrew Dara-AbramsView Answer on Stackoverflow
Solution 2 - Ruby on-RailsBudgieView Answer on Stackoverflow
Solution 3 - Ruby on-Railsuser708617View Answer on Stackoverflow
Solution 4 - Ruby on-RailsFlavio WuenscheView Answer on Stackoverflow
Solution 5 - Ruby on-RailsCody ElhardView Answer on Stackoverflow