LoginSignup
2
1

More than 3 years have passed since last update.

【RubyonRails】メッセージごとに異なるflashを表示する【Bootstrap】

Last updated at Posted at 2020-02-20

ポートフォリオを作る中で、bootstrapを利用したflashを実装したのでメモしておきます。

flashとは

そもそもflashとは何ぞやという人のために簡単に説明すると、Webサービスによくある「ログインに成功しました!」みたいなメッセージです。

railsではあれを簡単に実装できます。
さらにbootstrapを使えばデザインもいい感じに実装できます。

前提

  • deviseを導入している
  • bootstrapをgemで導入している

ヘルパーの設定

app/helpers/devise_helper.rbを作成し、以下のように記述してください。

app/helpers/devise_helper.rb
module DeviseHelper
    def bootstrap_alert(key)
        case key
        when "alert"
            "warning"
        when "notice"
            "success"
        when "error"
            "danger"
        end
    end
end

deviseに使われてるkeyをbootstrapのアラートごとに割り当てます。

app/views/layouts/_flashes.html.erb

app/views/layouts/_flashes.html.erbを作成して以下を記述。

app/views/layouts/_flashes.html.erb
<% flash.each do |key,value| %>
    <div class="alert alert-<%= bootstrap_alert(key) %>">
        <strong>
            <%= value %>
        </strong>
    </div>
<% end %> 

「 _ 」から始まるファイルは他ファイルでも共有できるようになっていますので、application.html.erbなどに

app/views/layouts/application.html.erb
<%= render layauts/flash %>

と記述してください。

これでflashが表示されたらOKです。

まとめ

webサイト作成時flashはなかなか切り離せないので、こんな風にbootstrapを利用して簡単に設定できるのは良いですね。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1