Header left Header right
 

Using the rails “flash” properly.

Published: September 27th, 2007

You know you love a good Rails tip when you see one, so here you go!

I’m sure many of you have had the problem of a flash message appearing on a weird page due to the way rails handles them. I never knew about the flash.now feature until I read this amazing post from the Thought Bot Blog.

So the rule is…

  • Use flash when you’re going to redirect, so that the next action will be able to display the flash value
  • Use flash.now when you’re going to render, so that the current view can display the value and the next view won’t (additionally and wrongly) display it.

I would also like to point out that a single flash area is atypical of a real world web application. Usually you have many partials on a single page and each of them call to a different controller action.

Instead of doing flash[:notice] all the time (and thus only having 1 flash point) or even looping through flash to diaply in a single flash point, instead do this:

(We have a login partial on the homepage, and this in the users controller)

flash[:partial_name_notice] = “Invalid password.”

(Then we have the homepage view that has a partial for login)

You can have many, many, many different flash points on each view so the user gets the notice where they expect it.

gravatar

[...] quote form daniel fischer’s blog [...]

Enter your comment

Ready. Set. Go.

In terms of the formatting, you're allowed to use markdown, textile, or basic html; it's truly up to you -- what strikes your fancy?

You don't have to worry about your e-mail address being sold to a russian-spam-mafia. I'm only going to use it for my own weird needs; like asking you out for a date on a lonely night of coding.