DEV Community

Shadiya
Shadiya

Posted on

Active Record Validations - Ruby on Rails

Validations are used to make sure that only valid data is saved to the database and Ruby on Rails provides us with a helpful guide. There a two types of validations, standard validations that rails gives us and also custom validations. Rails provides a number of commonly used validations. I will be covering how to implement both standard active record validations and custom validations.

Rails provide a us with a number of validation helpers that are commonly used. For example, in this method we have below, it checks if the instance we are trying to create has all of the attributes that we need. We want to make sure that it validates the presence of the name, and the numericality of the capacity:

Image description

There are a vast variety of different validations that could be implemented. You can also add a message that will come up if the validations are done incorrectly. Active record validations are really simple and easy to use with the help of the Ruby on Rails guide.

Custom Validations
To validate something that cannot be validated using by the Rails docs, you would have to use a custom validation method.
When you want to implement custom validations, you will use validate instead of validates (which is very important to remember) and add the method name that you will declare below it. Say, for example, you want to validate a users email we would create a custom validation.

To start, create a new folder in your app folder, app\validators. Inside of the new folder, create a new file, the name should describe what this specific code is supposed to do. Next, inside of the new file write a class that inherits from ActiveModel::EachValidator. Then, You will use the validators in the user model. It would look something like this:
Image description

Now we can start to write out our method in ActiveModel::EachValidator. We will use the value parameter to check the email:

Image description

Now this is what the final code should look like in the end.

Image description

Both the standard active record validations and the custom validations are quite simple to use.

Top comments (0)