jzofog
Last Updated: May 16, 2016
·
27.32K
· jbrooksuk
2a28c28368abb3b64141d4548c9eb2a6

Ruby on Rails Flash messages with Bootstrap

If you're using Ruby on Rails and Bootstrap originally from Twitter, then you may want to display flash messages with the alert styles. Here is a quick and easy way of doing so.

You just need to quickly extend application_helper.rb with the following:

def flash_class(level)
    case level
        when :notice then "alert alert-info"
        when :success then "alert alert-success"
        when :error then "alert alert-error"
        when :alert then "alert alert-error"
    end
end

Now when you call a flash message, you can use the following in your view:

<% flash.each do |key, value| %>
      <div class="<%= flash_class(key) %>">
            <%= value %>
      </div>
<% end %>

And just use:

flash[:success] = "Woohoo!"

As a success or:

flash[:alert] = "Alerting you to the monkey on your car!"

Tada!

5 Responses
Add your response

2454
D83b63db79b42978fe35e120550ca180

Or, if you are using twitter-bootstrap-rails gem, you can simply use bootstrap_flash helper - https://github.com/seyhunak/twitter-bootstrap-rails#flash-helper

over 1 year ago ·
13394
9b0f7bbf22d65fa2bd23496973c0ba80

Nice! And for other frameworks such as Semantic-UI is almost the same. Thanks!

over 1 year ago ·
13960
C20770a8670d0060b6ff022a8042d9a1

Since Rails 4.1 it does only work with strings for me, e.g.:

module ApplicationHelper
  def flash_class(level)
    case level
      when 'notice' then "alert alert-info"
      when 'success' then "alert alert-success"
      when 'error' then "alert alert-danger"
      when 'alert' then "alert alert-warning"
    end
  end
end
over 1 year ago ·
14291
D69adabd7f6f9898066e4e2047bdcd21

Thanx very simple - very usefull

over 1 year ago ·
15372
499df2d8dabd87c1b1c999ff07da2367

Thanks that helped !

over 1 year ago ·