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?
As said previously, validations ensure that only valid data goes to our database. For example, when you need a user to signup, you want the user to create a unique username, otherwise, it would troublesome to distinguish one user from another if they share the same username. That’s when validations come to work.
class User < ApplicationRecord validates :username, presence: true, uniqueness: trueendirb> User.create(username: "JohnD").valid?
=> trueirb> User.create(username: nil).valid?
=> falseirb> User.create(username: "JohnD").valid?
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
Be aware that not all methods trigger validations. For example,
User.new will not trigger validations, while
User.create will do so. Some of the methods that trigger validation are:
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.