The Power of Declarative Validation
You could write code that tests each property’s value as it arrives, and there may be times when you need to do that, but Rails offers a simpler approach that works for the vast majority of cases: declarative validation. (You can find the complete example shown here in ch07/guestbook005.)
Instead of checking to see if a value is present, for instance, you can just write:
# the name is mandatory
validates_presence_of :nameThe validates_presence_of
declaration activates Rails’ internal validation tools,
which can automatically block the addition of a record that’s missing a
name and report an error to the user, as shown in Figure 7-3.

Figure 7-3. Failing a simple validation
How did the model reach through the controller, all the way into the view, and make that happen? It’s worth walking back through once to trace the path Rails took. Example 7-3 shows the HTML that generated those messages.
Example 7-3. Model errors reported in HTML from the view
<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited thisperson from being saved</h2><p>There were problems with the followingfields:</p><ul><li>Name can't be blank</li></ul></div><form action="/people" class="new_person" id="new_person" method="post"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="b23eb784af45413f54bf73d49ea6eccd8115f3ee" /></div> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access