As the title of the question asks, I am interested in knowing if there is any difference when using flash[:error]
, flash[:alert]
, and flash[:notice]
. If so, when is it appropriate to use each, and why?
What are flash messages? A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions. Example messages: “Password changed correctly” (confirmation) “User not found” (error)
flash is a Rails mechanism to persist some information across 2 requests. You set something in flash hash in one request and it's available in the very next request you receive from that same client.
Since flash is just a "hash" you can use it like one. Which means you can provide your preferred key (:alert/:error/:notice) and put whatever message string you wish as the value.
The semantics of what or when to use :alert/:error/:notice are really up to you to manage. Having said that, the general best practice is to use :notice when things are OKAY and is displayed in a greenish hue, and use :error when things are NOT OKAY and is displayed in a reddish hue. It is completely okay if you want to use :alert for another type of message on your web app. I've used it before for informational purposes in a yellowish hue.
:alert
and :notice
functionally differ from other keys you invent. FlashHash
provides convenience accessors for the two: flash.alert
, flash.notice
. Rails' preference for these two further rears its way into redirect_to
which will only accept :alert
, :notice
, or :flash
.
However, a commit in July 2012 to edge Rails allows the privilege of adding other flash types. Here's an example of adding custom flash types in Rails 4:
# app/controllers/application_controller.rb class ApplicationController; add_flash_types(:error, :annoyance); end # app/controllers/monopoly_controller.rb class MonopolyController < ApplicationController def chance ... redirect_to haha_path, annoyance: "Go directly to jail. Do not pass Go. Do not collect $200." end end # app/views/haha/index.html.erb <%= annoyance %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With