Bootstrapではalertというクラスが用意されている。
<div class="alert alert-primary" role="alert"> This is a primary alert—check it out! </div> <div class="alert alert-secondary" role="alert"> This is a secondary alert—check it out! </div> <div class="alert alert-success" role="alert"> This is a success alert—check it out! </div> <div class="alert alert-danger" role="alert"> This is a danger alert—check it out! </div> <div class="alert alert-warning" role="alert"> This is a warning alert—check it out! </div> <div class="alert alert-info" role="alert"> This is a info alert—check it out! </div> <div class="alert alert-light" role="alert"> This is a light alert—check it out! </div> <div class="alert alert-dark" role="alert"> This is a dark alert—check it out! </div>
これをRailsのflashといい感じに混ぜたいって話
環境
設定
まず今回のキモのadd_flash_types
ApplicationController(app/views/layouts/application.html.erb)にadd_flash_typesを以下のように追加
class ApplicationController < ActionController::Base protect_from_forgery with: :exception add_flash_types :success, :info, :warning, :danger end
次はビューの設定。app/views/layouts/application.html.erbのbody内に以下を追加
<% flash.each do |name, msg| %> <div class="alert alert-<%= name %>"> <%= msg.html_safe %> </div> <% end %>
使いかた
redirect_to posts_path, success: '投稿に成功しました!'
マジでかんたんだは