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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay