Active Record validations

Validations are method calls on a model class that prevents data from being saved if that data does not seem right.

Active Record validates our data before it goes to the database so we don’t have data in our database.

Why should we use validations?

class User < ApplicationRecord  validates :username, presence: true, uniqueness: trueendirb> User.create(username: "JohnD").valid?
=> true
irb> User.create(username: nil).valid?
=> false
irb> User.create(username: "JohnD").valid?
=> false

As you can see above the user model says that our User is not valid if an username is not present and also requires the username to be unique . On the first try, we get back true because an username is present and because it’s the first time that username was used to create a user. In the second example, we get back false since we did not give our user a username. Lastly, on the third example, we get back false because the username JohnD already exists and our model requires usernames to be Unique .

Be aware that not all methods trigger validations. For example, will not trigger validations, while User.create will do so. Some of the methods that trigger validation are: create , save , update .

There are also Validation Helpers which provide validations rules. Some of those helpers are:

length : it validates the length of the values.

confirmation : should be used when you have two fields that should have the same contact.

There are many more helpers but the ones above are the ones I am familiar with. Validations are super important for coding since we want to avoid bad data getting into our database, validations make our database cleaner and help us avoid many problems.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store