Validations in Ruby on Rails

While building my first Ruby on Rails project I became very familiar with validations. Validations are very powerful tools that come through a gem provided by Rails called Active Record. These tools are used to ensure no bad data is being submitted to your database. For this, assume you have a full Rails application set up and a user class with the listed attributes: username, email, password. The User class would look something like:

User class w/o validations

Rails validations are used to ensure that only valid data is saved into your database. Validations are used as a barrier to entry for your database

User class w validations

The above example implements model-level validations on the User class. First I used the presence helper to ensure that the end-user has input both a username and email to signup. Next, I used the uniqueness helper to ensure that no two users can have the same username or email when signing up. For both helpers to work properly they need assigned to the condition of true. With these validations in place, if an end-user tries to submit the corresponding form without conforming to these validations then the instance will be marked as invalid and will not be saved to the database.

These are only a couple of validations that Active Record includes. Another example includes a validation of input length that could be a minimum or maximum of characters.

User class w min/max validations

Again, there is so much you can do with Active Record validations including creating custom validations where you get to dictate what is valid or invalid. I hope this was some help with getting started with validations through Active Record on your future Ruby on Rails applications.