Implementing Flash Messages to your Website

Whenever you redirect someone in your website it is a good idea to use a flash message to let them know that what they just did worked. For example if a user is editing content in your website and after they are done, your site redirects them to the homepage, without a flash message, some users might think that something went wrong, but if you send them a flash message saying ‘message edited successfully!’ they will know that everything worked out. There are four main types of flash messages, as shown in the picture below: success, info, warning, and danger. changing the class to include one of these words will change the bootstrap flash message display dynamically.

This is the html i implemented in my application.html.erb page:

<div class=’container’>
<% flash.each do |name, message| %>
<div class=”alert alert-<%= name %> alert-dismissible” role=”alert”>
<button type=”button” class=”close” data-dismiss=”alert” aria-label=”Close”><span aria-hidden=”true”>&times;</span></button>
<%= message %>
</div>
<% end %>
</div>

In this code, name and message are variables that will be decided in your controller methods through hash utilized in a controller method before a redirect or render of an html page. The ‘name’ variable is one of the four alert message types (success, danger, info, warning) and the message variable is the text content within the flash message. Some of the other code is the css and bootstrap features of the flash message box, as well as a feature allowing the user to delete the flash message dynamically on the redirect page. Below is an example of you I used flash message in my controller to notify a user that they successfully added a product to my store:

def create
product = Product.new(
name: params[“name”],
price: params[“price”],
description: params[“description”],
supplier_id: rand(1..2)
)
product.save
image = Image.new(
url: params[“url”],
product_id: product.id
)
image.save

flash[:success] = “Product Successfully Added!”
redirect_to ‘/products’
end

The line in bold is the code used to assign each of the variables utilized in the dynamic html, in this case name = success and message = Product Successfully Added. Now on my site when a user adds a product they know it worked!

Like what you read? Give Justin Skord a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.