Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference when using flash :error, :alert, and :notice?

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?

like image 620
Guillermo Gomez Avatar asked Apr 27 '11 02:04

Guillermo Gomez


People also ask

What is a flash error message?

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)


2 Answers

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.

like image 140
Aditya Sanghi Avatar answered Oct 12 '22 13:10

Aditya Sanghi


: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 %> 
like image 34
fny Avatar answered Oct 12 '22 12:10

fny