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 :name

The 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.

Failing a simple validation

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 this
person from being saved</h2><p>There were problems with the following
fields:</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" ...

Get Learning Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.