Home > Articles

Effectively Use Rails 5 Validation Methods

  • Print
  • + Share This
One of the most appealing aspects of Rails is how we can declaratively specify the criteria for determining the validity of model objects. In this excerpt, the ActiveRecord Validations API is covered in-depth.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

This chapter is from the book

This chapter is from the book

  • I have bought this wonderful machine—a computer. Now I am rather an authority on gods, so I identified the machine—it seems to me to be an Old Testament god with a lot of rules and no mercy.

  • —Joseph Campbell

The Validations API in Active Model, along with its supplementary functionality in Active Record allows you to declaratively define valid states for your model objects. The validation methods hook into the life cycle of an Active Record model object and are able to inspect the object to determine whether certain attributes are set, have values in a given range, or pass any other logical hurdles that you specify.

In this chapter, we’ll describe the validation methods available and how to use them effectively. We’ll also explore how those validation methods interact with your model’s attributes and how the built-in error-messaging system messages can be used effectively in your application’s user interface to provide descriptive feedback.

Finally, we’ll cover how to use Active Model’s validation functionality in your own, non-Active Record classes.

8.1 Finding Errors

Validation problems are also known as (drumroll please . . .) errors! Every Active Record model object contains a collection of errors, accessible (unsurprisingly) as the errors attribute.

When a model object is valid, the errors collection is empty. In fact, when you call valid? on a model object, a series of steps to find errors is taken as follows (slightly simplified):

  1. Clear the errors collection.

  2. Run validations.

  3. Return whether the model’s errors collection is now empty or not.

If the errors collection ends up empty, the object is valid. In cases where you have to write actual validation logic yourself, you mark an object invalid by adding items to the errors collection using its add methods. Simple as that.

We’ll cover the methods of the Errors class in some more detail later on. It makes more sense to look at the validation methods themselves first.

  • + Share This
  • 🔖 Save To Your Account