Bootstrap 4.1 alerts in Rails 5 Apps

The Bootstrap 4.1 doc shows different alerts available, the ones that are relevant to Rails are:

<div class="alert alert-info" role="alert">
  info
</div>
<div class="alert alert-success" role="alert">
  success
</div>
<div class="alert alert-danger" role="alert">
  danger
</div>
<div class="alert alert-warning" role="alert">
  warning
</div>

In the controller, you can do:

flash[:success] = "Payment success!"

or

flash[:alert] = "We will be rebooting your machine now!"

Define a helper method In application_helper.rb:

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

Using symbol in the case-when does not work. Add the flash notice to the application layout.

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

  <%= yield %>
</div>

You will now have Bootstrap 4.1 style alerts in Rails app.

Reference

Ruby on Rails Flash Messages with Bootstrap


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.