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
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
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
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"
The result:
cat = SchrodingersCat.new(alive: nil)
cat.valid? # => false
cat.errors.to_a # => ["Alive must be boolean"]
Top comments (0)