LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】toastrでフラッシュメッセージを表示

Last updated at Posted at 2021-08-05

ポートフォリオを作成中、手軽にフラッシュメッセージをおしゃれにしたくて
何か便利なGemないかなと探していたらtoastrというものがあったので、導入しました。
jQuery導入が前提です。

Gemの追加

まず、Gemをインストール

Gemfile
gem 'toastr'
bundle install

toastrJavaScriptSassに読み込ませます。

assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery
//= require jquery3
//= require jquery_ujs
//= require popper
//= require bootstrap
//= require data-confirm-modal
//= require toastr #追加
//= require_tree .
app/assets/stylesheets/application.scss
@import "toastr"; #追加

実装

application.html.erbに記述します。

app/views/layouts/application.html.erb
<% if flash.any? %>
  <script type="text/javascript">
    <% flash.each do |key, value| %>
      <% key = "success" if key == "notice" %>
      <% key = "error" if key == "alert" %>
      toastr['<%= key %>']('<%= value %>');
    <% end %>
  </script>
<% end %>

私はDeviseを使用しているので、フラッシュメッセージのシンボルは:notice:alertです。
ですが、toastrのメソッドはsuccesserrorなので、noticesuccessに、alerterror変換してあげましょう。
toastrは他にもwarninginfoのメソッドがあります。
メソッドによって色が変わるので可愛いです!

aa86aec839ba4af2e3aa0e4a6a8ed89d.png
3eab0142edef9164c0b02f9ef09ff95e.png

こんな感じで表示されました!

0
0
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
0
0