The Rails flash is typically used for short messages:
But it can be used for more than that, any time that you redirect and want to pass along some state without making it part of the URL.
These are some things I’ve used it for.
Identifiers for more complex messages
Maybe you want to show a more complex message after signing up, containing things like links and bullet points.
Rather than send all that in the flash, you can send some identifier that your views know how to handle.
This could be the name of a partial:
1 2 3 4 5 6 7
1 2 3 4
Or just a flag:
Pass on the referer
Say you have some filter redirecting incoming requests. Maybe you’re detecting the locale and adding it to the URL, or verifying credentials.
You can use the flash to make sure the redirected-to controller gets the original referer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Now, any controller that cares about the referer could get it with
Google Analytics events
Send event data from the controller:
1 2 3 4 5 6 7
1 2 3 4 5
The flash vs. params
You may have considered that any of the above could have be done with query parameters instead. Including common flash messages:
Using the flash means that the passed data doesn’t show in the URL, so it won’t happen twice if the link is shared, bookmarked or reloaded. Also the URL will be a little cleaner.
Additionally, the user can’t manipulate the flash, as it’s stored in the session. This adds some protection. If the flash partial example above used
params, a user could pass in
../../admin/some_partial to see things they shouldn’t.
I’d love to hear about what unconventional uses you’ve put the flash to!