DEV Community

Cover image for TIL Presence Validation on Boolean Column
Carlos Augusto de Medeir Filho
Carlos Augusto de Medeir Filho

Posted on

3 2

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay