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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

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