DEV Community

Cover image for Boolean Validator for Rails
Mario
Mario

Posted on β€’ Edited on

1

Boolean Validator for Rails

Rails doesn't come with a built-in boolean validator.
That means if we have boolean attribute and we set it to nil, it defaults to false, which is not necessarily what we want.

For example a SchrodingersCat model with a alive boolean attribute:

cat = SchrodingersCat.new(alive: nil)
cat.valid? # => true
Enter fullscreen mode Exit fullscreen mode

To solve that problem we can add a custom validator:

# app/validators/boolean_validator.rb
class BooleanValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.in? [false, true]

    record.errors.add attribute, :boolean
  end
end
Enter fullscreen mode Exit fullscreen mode

Then we can use that validator the same way as the built-in ones:

# app/models/schrodingers_cat.rb
class SchrodingersCat < ApplicationRecord
  validates :alive, boolean: true
end
Enter fullscreen mode Exit fullscreen mode

The error message can be defined for example in activerecord.errors.messages.boolean:

# config/locales/en.yml
en:
  activerecord:
    errors:
      messages:
        boolean: "must be boolean"
Enter fullscreen mode Exit fullscreen mode

The result:

cat = SchrodingersCat.new(alive: nil)
cat.valid? # => false
cat.errors.to_a # => ["Alive must be boolean"]
Enter fullscreen mode Exit fullscreen mode
πŸ’‘ One last tip before you go

Tired of spending so much on your side projects? πŸ˜’

Just one of many great perks of being part of the network ❀️

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay