6.2 User validations

The User model we created in Section 6.1 now has working name and email
attributes, but they are completely generic: any string (including an
empty one) is currently valid in either case. And yet, names and email
addresses are more specific than this. For example, name should be
non-blank, and email should match the specific format characteristic of
email addresses. Moreover, since we’ll be using email addresses as
unique usernames when users sign in, we shouldn’t allow email duplicates
in the database.

In short, we shouldn’t allow name and email to be just any strings; we
should enforce certain constraints on their values. Active Record allows
us to impose such constraints using validations. In this section, we’ll
cover several of the most common cases, validating presence, length,
format and uniqueness. In Section 6.3.4 we’ll add a final common
validation, confirmation. And we’ll see in Section 7.3 how validations
give us convenient error messages when users make submissions that
violate them.
6.3 Adding a secure password

In this section, we’ll add the last of the basic User attributes: a
secure password used to authenticate users of the sample application.
The method is to require each user to have a password (with a password
confirmation), and then store a hashed version of the password in the
database. (There is some potential for confusion here. In the present
context, a hash refers not to the Ruby data structure from Section 4.3.3
but rather to the result of applying a irreversible hash function to
input data.) We’ll also add a way to authenticate a user based on a
given password, a method we’ll use in Chapter 8 to allow users to sign
in to the site.

The method for authenticating users will be to take a submitted
password, hash it, and compare the result to the hashed value stored in
the database. If the two match, then the submitted password is correct
and the user is authenticated. By comparing hashed values instead of raw
passwords, we will be able to authenticate users without storing the
passwords themselves. This means that, even if our database is
compromised, our users’ passwords will still be secure