Use of Flash in Rails
In rails, flash is also used as a session management method. Its feature is that it gets cleared after every request. It is basically used when we just want to show a message in the next request or view and don't want to use any extra instance variable for that purpose. It can be better understood with an example ,i.e. Suppose there is a user, who is not authorized to view the admin panel page, so if he hits that URL, he will be redirect to another page with a message "You are not authorized to go the admin page". In these kind of situations flash is used. In the code it will be used like this:
class AdminController < ApplicationController
def admin_page
if !user.is_admin?
flash[:notice] = "You are not authorized to go the admin page"
redirect_to root_url
end
end
end
In the root home page you can access the flash variable as:
<html>
<head>
</head>
<body>
<% if flash[:notice].present? %>
<div class="notice">
<%= flash[:notice] %>
</div>
<% end %>
</body>
</html>
If you want to have flash variable in the same request(as flash gets available in the next request), i.e. to show an error message on wrong form submission, flash.now is used as:
flash.now[:error] = "Invalid Phone Number"
0 Comment(s)