When I was first learning Ruby, I used a variety of if/else statements to “validate” user input and prevent breakage in my CLI applications. I’m sure you can understand this was not the most efficient way to go about safeguarding your code — though it was prior to learning the ultra-powerful, time and energy-saving, omniscient Active Record. In this post, I’m going to outline the importance of using validations and some of my most used Active Record Validations helpers.

Why Validations?

Validations are used to ensure only valid data is persisted to your database. For example, you’re helping Joe Biden’s 2020 presidential campaign and want to collect the names and phone numbers of all Trump supporters you know. You want to send an automated voice recording that outlines the Trump administration’s obscene failures in handling the COVID-19 pandemic (they deserve to know). Little did you know, Putin found out about your mission and started typing alphabetic characters in your phone number input field. CRAP! Your program breaks because 408-RUSSIA-IS-AWESOME is not a valid phone number.

Image for post

Photo by Jørgen Håland on Unsplash

It’s worth noting: there are many ways to validate data in a Ruby program, but according to Ruby documentation, model-level validations are the most appropriate in most circumstances.

As you may know, saving an object that correlates to a row in your database is a 2 step process in Active Record. First, the object is instantiated.

trump_supporter = User.new("Kanye", 323-290-5589)

Second, the object is saved and persisted in the database.

trump_supporter.save

The moment you save the object to the database, Active Record validations are triggered. This is why it is typically good practice to separate instantiation and saving for better error handling — as opposed to lumping them together using Active Record’s _.create_. The following methods will trigger a validation:

.create
.create!
.save
.save!
.update
.update!

#activerecord #technical-writing #validation #ruby-on-rails #ruby

Active Record Validations
1.15 GEEK