DEV Community

Josephine Luu
Josephine Luu

Posted on

Rails: Active Record Validation Helpers

Why do we use validations?

Validations are used to ensure that data you want is saved correctly into your database. For example, you wouldn't want someone to put a phone number in a email form.

Image description

Validation Helpers

I'll be going over some validation helpers along with some examples provided.

1. presence

Image description

In line 3, this is how you would use presence. This is saying
that a name has to be there. If a user were to try and
create a mission without a name, it wouldn't work.

2. uniqueness

Image description

This is saying that a email has to be unique.

3. length

Image description

With each of these, it can have a minimum, maximum, in, and is. Minimum and maximum is pretty self explanatory. For in, it's saying that the password has to be a length within 6 to 20 characters. As for is, it has to be 6 characters exactly.

4. inclusion

Image description

In line 2, this is saying that strength can only be strong, weak, or average. In rails console, if you enter %w(Strong Weak Average), it will give you an array.

Image description

In line 3, it's saying the age has to be between 8 and 18.

These are just a few active record validations, but if you are interested in looking at more, I would visit here. Thanks for reading and good luck coding!

sources: https://guides.rubyonrails.org/active_record_validations.html

Top comments (0)