Understanding ActiveRecord Validations with Ruby on Rails

Jordan T Romero
7 min readAug 23, 2020
photo credit Cookie the Pom

What are validations and how are they useful?

Validations are essential to a Rails application. They allow us to control the information that is being saved into our database. They are given to us through Active Record and allow us to be thoughtful about how we save data. There are many ways that you can control database information. You can use client-side validations and controller-level validations, but the Rails team favors model-level validations for a multitude of reasons. They are database agnostic, meaning that they can be used with various systems and are not customized for a single system. They cannot be bypassed by users. They are convenient to test and maintain.

Validations are triggered on .save or .valid?. In other words, validations are only triggered when we are attempting to persist data to the database. Active Record is doing a lot for us behind the scenes. It gives us a method called new_record? that checks the database to see if the record exists in our database and will return true if it’s new. Below is an example of the console output testing this method:

$ rails console>> b = Book.new(name: "A Tale of Two Cities")=> #<Book id: nil, name: "A Tale of Two Cities", created_at: nil, updated_at

--

--

Jordan T Romero

Full Stack Developer. Designs solutions combining analytical, technical, and problem-solving skills to make ideas come to life.