Chapter 7. Strengthening Models with Validation

At this point, you have most of the ingredients needed to create simple web applications in Rails, provided you’re willing to stick to a single database table. There’s one large problem remaining: users (and programs connecting through web services) don’t always put in the data you want them to put in. Making your application work reliably requires checking information as it comes in and interacting with users so that they know how to get it right.

Warning

As you’ll see throughout this chapter, Rails expects all data validation to happen in the model layer and provides tools that make it easy to do there. If you find yourself putting data-checking code into the views or the controllers, pause for a moment—you’re quite likely doing something wrong.

The one probable exception is if you’re adding warnings for users working in your forms, avoiding a round trip to the server, but you should never rely on those to limit your data to the correct types. All that work should do is give users more information more rapidly.

Without Validation

You might think, since the examples in Chapter 6 defined data types, that Rails will be doing some basic content checking—ensuring that numeric data actually includes numbers, for example.

Nope. Rails and the Rails scaffolding give you places where you can add validation code, but absolutely none of it is built-in. The easiest way to see what happens is to try putting in bad data, as shown in Figure 7-1.

Figure 7-1. Entering ...

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.