Displaying Error Messages with the Action Pack Library
In this ninth part of a multi-part series on the Action Pack library for Rails, you'll learn how to displya error messages in templates, and more. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Displaying Error Messages with the Action Pack Library (Page 1 of 2 )
Displaying Error Messages in Templates
Let’s try submitting the form again. Make sure you leave the form empty so you can see whether the validations are working as expected. Sure enough, the form doesn’t save. In fact, you’ll notice that you’re still on the same screen and that the form elements are highlighted in red, as shown in Figure 6-2.
Figure 6-2. Fields that fail validation and highlighted in red.
If you look at the HTML source, you’ll see that the input tags are surrounded by div elements with the class name fieldWithErrors :
Rails does this automatically for any fields that failed validation, and you can use these classes to style invalid elements.
Note The style rules that turn the invalid fields red are generated by the scaffold generator and are in public/stylesheets/scaffold.css . All static files, such as stylesheets and images, are located in the public directory.
But wait a minute. Where is the formatted list of errors that we got with our invalid events? Well, the scaffold generator added the helper that displays these, but if we want them to show up here, we’ll have to do it ourselves. We’ll use the error_messages_for helper and tell it the name of the model whose errors we want to see—in this case, User . Add the following to the top of the new template in app/views/users/new.rhtml :
<%= error_messages_for :user %>
Now submit the form one more time, again with empty fields. You should see the error messages, as shown in Figure 6-3.
Figure 6-3.Error messages for invalid events
With all the plumbing in place, let’s submit the form with valid data. If all goes according to plan, the new user should be created, and you’ll be redirected to the events controller, where you’ll see the friendly flash message we set. Notice that if you refresh the page using your browser’s refresh button, the flash message will disappear.