Ruby On Rails Lesson
Rendering with a Flash Message
Recall from Section 7.3.2 that we displayed signup errors using the User model error messages. These errors are associated with a particular Active Record object, but this strategy won’t work here because the session isn’t an Active Record model. Instead, we’ll put a message in the flash to be displayed upon failed signin. A first, slightly incorrect, attempt appears in Listing 8.10.
Because of the flash message display in thesitelayout (Listing 7.26), the flash[:error] message automatically gets displayed; because of the Bootstrap CSS, it automatically gets nice styling (Figure 8.6).
Unfortunately, as noted in the text and in the comment in Listing 8.10, this code isn’t quite right. The page looks fine, though, so what’s the problem? The issue is that the contents of the flash persist for one request, but—unlike a redirect, which we used in Listing 7.27—re-rendering a template with render doesn’t count as a request. The result is that the flash message persists one request longer than we want. For example, if we submit invalid information, the flash is set and gets displayed on the signin page (Figure 8.6); if we then click on another page, such as the Home page, that’s the first request since the form submission, and the flash gets displayed again (Figure 8.7).
Figure 8.6 The flash message for a failed signin.