1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails6でNotification "Noty"の導入

Last updated at Posted at 2019-09-03

RailsでのNotificationと言えば、torstrが定番ですが、Rails6では、うまく動かなかったので、Notyを使ってみました。

Screen Recording 2019-09-03 at 12.05 PM.gif

Screen Recording 2019-09-03 at 12.04 PM.gif

yarnで導入できるし、書き方もtorstrと似ているので、簡単です。

インストール

$ yarn add noty

###各記述

app/javascript/packs/application.js
window.Noty = require('noty');
app/assets/styleseets/application.css
@import "noty/lib/noty";
@import "noty/lib/themes/sunset";

###パーシャル

_notification.html.erb
<% unless flash.empty?  %>
  <script>
    <% flash.each do |key, value| %>
      <% type = key.to_s.gsub('alert', 'error').gsub('notice', 'success') %>
      new Noty({
          type: '<%= type %>',
          layout: 'topRight',
          timeout: 3000,
          theme: 'sunset',
          text: '<%= value %>'
      }).show();
    <% end %>
  </script>
<% end %>
_error_messsags.html.erb
<% if resource.errors.any? %>
  <script>
      <% resource.errors.full_messages.each do |message| %>
      new Noty({
          type: 'error',
          layout: 'topRight',
          timeout: 3000,
          theme: 'sunset',
          text: '<%= message %>'
      }).show();
      <% end %>
  </script>
<% end %>

あとは、表示させたいviewに読み込ませるだけ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?