DEV Community

Max
Max

Posted on

Basics of Active Record Validations

Introduction

Ruby on Rails ('Rails') is a web app development framework that provides a foundation for developers to build on. Rails provides tools that make common development tasks easier. For instance: managing a database. Rails provides Active Record to facilitate the management of data; it acts as the model in MVC1. Active Record is an ORM (Object Relational Mapper) that simplifies database creation, data associations, and data validations. Data validations protect our application from user error and malicious attempts at manipulation. Before explaining validations themselves, we'll cover the difference between invalid and valid data. If you want to jump straight into validations, click here.

Invalid vs Valid Data

Our applications do not exist in a vacuum. We will ideally have real people using and interacting with our programs constantly. In a perfect world, everyone would know our intentions as developers when asking for user input in things like a username, email, phone number, etc. However, our intentions are not always clear, and our users will inevitably make mistakes like forgetting a digit in their phone number or leaving a username field blank.

Additionally, malicious users may make bad faith attempts to use our program to access otherwise unauthorized data. For example, someone may attempt to gain admin privileges by creating a request to create an account with an 'admin' parameter.
In either case, we could call these examples of 'invalid data' - information that does not match our intentions when asking for user input.

By contrast, valid data meets the developer's intentions and allows our applications to run smoothly. Knowing this, how can we prevent invalid data from entering our database? Through Active Record, we have Validations.

Validations

Validations are rules for a model that declare whether or not data is valid based on specified criteria. Validations are run on the create, save, and update methods and their bang versions (create!, save!, update!).

Active Record provides pre-defined 'validation helpers' that provide common rules for validation. There are many validation helpers, but the names for them are fairly self-explanatory. Generally, the syntax for implementing validations is validates :model_attribute, validation_helper: {helper_options}

Validation Practice Example

Suppose you work at a school and you are working on creating an application to track students and their classes. In this example, we'll create the model for students.

You'd want to prevent users from having the same username, and at minimum we would expect a student's profile to have a username and a name. While passwords are also an intuitive necessity, user authentication will be ignored to keep this example focused on data validation.

class User< ApplicationRecord
validates :username, :name, presence: true
validates :username, uniqueness: true
validates :username, length: {minimum: 4}
validates :age, inclusion: {in: (10..16)}

end
Enter fullscreen mode Exit fullscreen mode

Here in our User model we've added validations so that :username and :name are present (the values are neither nil or a blank string), :username is unique among all other values of :username for the User model, :username is at least four characters long, and that the value of :age is included between the range 10-16.

Now if we try to create a User without providing any parameter we will see that User.create() will be unsuccessful.

User.create()
=>#SQL queries
#<User:0x000055b999d51670 id: nil, username: nil, name: nil, age: nil, created_at: nil, updated_at: nil>
Enter fullscreen mode Exit fullscreen mode

You can see that our program attempted to run the necessary SQL queries for our database, but since our returned object lacks an :id we can tell it was unsuccessful. Now, only valid parameters will allow for the creation of a model instance and save it to the database.

User.create(username:"upDog", name:"John", age:10)
=> #A series of SQL queries
   #<User:0x0000558262db3410 id: 1, username: "upDog", name: "John", age: 10>
Enter fullscreen mode Exit fullscreen mode

Since the parameters pass the validations specified in our model, the object was properly saved and now has an id.

Error Handling

Validations also provide error messages upon failure if you use the bang versions of our method calls. Error handling is useful as we may want to alert our users to why their attempts are unsuccessful.

User.create!()
=>#`raise_validation_error': Validation failed: Username can't be blank, Name can't be blank, Username is too short (minimum is 4 characters), Age is not included in the list (ActiveRecord::RecordInvalid)
Enter fullscreen mode Exit fullscreen mode

By using the bang versions of create, update, and save, a special Exception Object will be raised which will detail why validations failed. We can then return this information to our Controller and render the messages to our prospective new user.

Conclusion

Rails provides many tools that simplify common tasks so that you can focus on the more complex and fun parts of your application. With Active Record, we can ensure only valid data is kept in our database through the use of validations. Validations check if parameters passed to the create , update , and save methods meet criteria specified in our Model. If the parameters don't pass our validations, we can send error messages to our user and inform them of needed corrections.

1 : MVC, Model-View-Controller, is an architectural design pattern often used in web development

Top comments (0)