Last Updated: February 25, 2016
·
1.039K
· mdepolli

Bootstrap 2.1+ updated alerts in Rails

You probably already used a helper to output flash messages in Rails using nice pre-Bootstrap 2.1 alerts. But look! Now we have a little bit more code with the closing button and all that. Time for an update!

This solution has the added plus of leaving your views extremely clean. And it allows you to easily add support to your own flash messages other than the dreary old :notice and :alert.

In app/helpers/application_helper.rb

def flash_message
  types = { :notice => 'success', :alert => 'error', :info => 'info' }
  flash.inject("") do |sum, message|
    content_tag :div, :class => "alert alert-#{types[message[0]]}" do
      button_tag('×'.html_safe, :type => 'button', :class => 'close', :'data-dismiss' => 'alert', :name => nil) +
      message[1]
    end
  end
end

And then in your views, preferably a layout such as app/views/layouts/application.html.erb

<%= flash_message %>

That's all you need to start displaying your flash messages in shiny new updated Bootstrap alerts. You can keep calling them the same way you're used to, by using flash[:notice] = "Your new lemur family is already on their way to your place!"