Handy cheat sheet for flash messages in Rails

Mayurkumar Patel
1 min readApr 5, 2017

--

CSS code:

#flash-messages-section{
position: absolute;
z-index: 9999;
width: 100%;
}

JavaScript code

$(document).on('turbolinks:load',function(){
setTimeout(function() {
$('#flash-messages-section').slideUp('500');
}, 5000);
});

Application Helper code

# app/helpers/application_helper.rb
def flash_class(level)
case level.to_sym
when :notice then "alert alert-success"
when :success then "alert alert-success"
when :error then "alert alert-danger"
when :alert then "alert alert-danger"
when :warning then "alert alert-warning"
end
end
def flash_prefix(level)
case level.to_sym
when :notice then "Success!"
when :success then "Success!"
when :error then "Error!"
when :alert then "Alert!"
when :warning then "Warning!"
end
end

HTML code

# app/views/shared/_flash_message.html.erb
<div id="flash-messages-section">
<% flash.each do |key, value| %>
<div class="<%= flash_class(key) %> no-radius fade in">
<a href="#" data-dismiss="alert" class="close">×</a>
<ul>
<li>
<strong><%= flash_prefix(key)%></strong>&nbsp;<%= value %>
</li>
</ul>
</div>
<% end %>
</div>

Implementation of above setup.

# in controller:
def create
@role = Role.new(role_params)
respond_to do |format|
if @role.save
format.html { redirect_to roles_path, notice: 'Role was successfully created.' }
format.json { render :show, status: :created, location: @role }
else
format.html { render :new }
format.json { render json: @role.errors, status: :unprocessable_entity }
end
end
end
# app/views/layouts/application.html.erb
<body>
<%= render "shared/flash_message" %>
<%= yield %>
</body>

--

--

Mayurkumar Patel
Mayurkumar Patel

Written by Mayurkumar Patel

helping companies to take the stress out of software development and make their business shine.

No responses yet