DEV Community

Cover image for TIL Presence Validation on Boolean Column

TIL Presence Validation on Boolean Column

Hello, I am Carlos Augusto de Medeiros Filho. This is a short post on what I learned today about rails model validations. I usually write those posts to my future self and to consolidate the knowledge in my brain. I hope you find it useful.

The standard way of validating the presence

Rails give us a way to validate the presence of the model attributes.

For instance, imagine we have a User model with a column named age. We want to raise an error every time we try to save an instance of User in the database before sending the query.

One way to do it would be:

class User < ApplicationRecord
  validates :age, presence: true
end
Enter fullscreen mode Exit fullscreen mode

Rails checks the presence/absence of the property by using the #blank? method.
However, the way this method handles boolean values may be a little bit misleading. See below:

false.blank? # => true
Enter fullscreen mode Exit fullscreen mode

Solution

A possible solution would be that instead of checking the presence per se, we could check if the value is one of the values we pass in as a list, in this case [true, false].

Imagine that our User has a column that defines if that user is an admin or not named is_admin. We can check the presence, or the inclusion of the value of this property is true or false, meaning that we can't have a nil value for is_admin.

class User < ApplicationRecord
  validates :is_admin, inclusion: { in: [ true, false ] }
end
Enter fullscreen mode Exit fullscreen mode

Discussion (0)