学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails6.0 | 民泊予約サイトの構築 | 08| フラッシュメッセージ(noty)

[07]氏名認証<< [ホームに戻る] >> [09]Gメール


notyのデザインについては以下を参照して下さい。
ned.im


notyはyarnを使ってインストールします。


コマンド
yarn add noty


「app\javascript\packs\application.js」に以下の記述を追加します。


記述追加 app\javascript\packs\application.js(11行目)

window.Noty = require("noty")



app\javascript\packs\application.js

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

window.Noty = require("noty")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)



「app\assets\stylesheets\application.scss」ファイルに以下の記述を追加します。


記述追加 app\assets\stylesheets\application.scss(20行目)

 @import 'noty/lib/noty';
 @import 'noty/lib/themes/sunset';



app\assets\stylesheets\application.scss

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
 
 @import 'bulma';
 @import 'bulma-extensions';

 @import 'noty/lib/noty';
 @import 'noty/lib/themes/sunset';



「app\views\shared」フォルダに「_notification.html.erb」ファイルを新規作成します。


app\views\shared\_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 %>



「app\views\layouts\application.html.erb」ファイルの16,17行目の記述を削除し、そこに「<%= render 'shared/notification' %>」の記述を追加します。


削除する記述 app\views\layouts\application.html.erb(16,17行目)

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>


記述更新 app\views\layouts\application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Minpaku6</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>

    <!-- ナビゲーションバー -->
    <%= render  "shared/navbar" %>

    <!-- noty -->
    <%= render 'shared/notification' %>

    <%= yield %>
  </body>
</html>



フラッシュメッセージを日本語化します。


記述追加 GemFile(64行目)

gem 'rails-i18n'



GemFile

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

# Bulma
gem 'bulma-rails', '~> 0.7.4'
gem 'bulma-extensions-rails', '~> 1.0.30'

#デバイス
gem 'devise'

# 日本語化
gem 'rails-i18n'



コマンド
bundle


「config\locales」フォルダに「devise.ja.yml」ファイルを新規作成します。


config\locales\devise.ja.yml(新規作成したファイル)

ja:
  devise:
    confirmations:
      confirmed: 'アカウントを登録しました。'
      send_instructions: 'アカウントの有効化について数分以内にメールでご連絡します。'
      send_paranoid_instructions: "あなたのメールアドレスが登録済みの場合、本人確認用のメールが数分以内に送信されます。"
    failure:
      already_authenticated: 'すでにログインしています。'
      inactive: 'アカウントが有効化されていません。メールに記載された手順にしたがって、アカウントを有効化してください。'
      invalid: "%{authentication_keys} もしくはパスワードが不正です。"
      locked: 'あなたのアカウントは凍結されています。'
      last_attempt: 'あなたのアカウントが凍結される前に、複数回の操作がおこなわれています。'
      not_found_in_database: "%{authentication_keys} もしくはパスワードが不正です。"
      timeout: 'セッションがタイムアウトしました。もう一度ログインしてください。'
      unauthenticated: 'アカウント登録もしくはログインしてください。'
      unconfirmed: 'メールアドレスの本人確認が必要です。'
    mailer:
      confirmation_instructions:
        subject: 'アカウントの有効化について'
      reset_password_instructions:
        subject: 'パスワードの再設定について'
      unlock_instructions:
        subject: 'アカウントの凍結解除について'
      password_change:
        subject: 'パスワードの変更について'
    omniauth_callbacks:
      failure: "%{kind} アカウントによる認証に失敗しました。理由:(%{reason})"
      success: "%{kind} アカウントによる認証に成功しました。"
    passwords:
      no_token: "このページにはアクセスできません。パスワード再設定メールのリンクからアクセスされた場合には、URL をご確認ください。"
      send_instructions: 'パスワードの再設定について数分以内にメールでご連絡いたします。'
      send_paranoid_instructions: "あなたのメールアドレスが登録済みの場合、パスワード再設定用のメールが数分以内に送信されます。"
      updated: 'パスワードが正しく変更されました。'
      updated_not_active: 'パスワードが正しく変更されました。'
    registrations:
      destroyed: 'アカウントを削除しました。またのご利用をお待ちしております。'
      signed_up: 'アカウント登録が完了しました。'
      signed_up_but_inactive: 'ログインするためには、アカウントを有効化してください。'
      signed_up_but_locked: 'アカウントが凍結されているためログインできません。'
      signed_up_but_unconfirmed: '本人確認用のメールを送信しました。メール内のリンクからアカウントを有効化させてください。'
      update_needs_confirmation: 'アカウント情報を変更しました。変更されたメールアドレスの本人確認のため、本人確認用メールより確認処理をおこなってください。'
      updated: 'アカウント情報を変更しました。'
    sessions:
      signed_in: 'ログインしました。'
      signed_out: 'ログアウトしました。'
      already_signed_out: '既にログアウト済みです。'
    unlocks:
      send_instructions: 'アカウントの凍結解除方法を数分以内にメールでご連絡します。'
      send_paranoid_instructions: 'アカウントが見つかった場合、アカウントの凍結解除方法を数分以内にメールでご連絡します。'
      unlocked: 'アカウントを凍結解除しました。'
  errors:
    messages:
      already_confirmed: 'は既に登録済みです。ログインしてください。'
      confirmation_period_expired: "の期限が切れました。%{period} までに確認する必要があります。 新しくリクエストしてください。"
      expired: 'の有効期限が切れました。新しくリクエストしてください。'
      not_found: 'は見つかりませんでした。'
      not_locked: 'は凍結されていません。'
      not_saved:
        one: "エラーが発生したため %{resource} は保存されませんでした:"
        other: "%{count} 件のエラーが発生したため %{resource} は保存されませんでした:"



記述追加 config\application.rb
20行目に「config.i18n.default_locale = :ja」の記述を追加しています。
23行目に「config.time_zone = 'Tokyo'」の記述を追加しています。

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Minpaku6
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.

    # 日本語化
    config.i18n.default_locale = :ja

    # 標準時間を東京に設定
    config.time_zone = 'Tokyo'

  end
end



バリデーションのメッセージもnotyで表示できるようにします。


記述更新 app\views\devise\shared\_error_messages.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 %>



ブラウザ確認
http://localhost:3000/

noty
noty



バリデーションの日本語化、日付フォーマットを設定しておきます。


「config\locales」フォルダに「ja.yml」ファイルを新規作成して下さい。


config\locales\ja.yml(新規作成したファイル)

ja:
  activerecord:
    attributes:
      user:
        full_name: 氏名
        current_password: パスワード
        password_confirmation: パスワードの確認
        password: パスワード
        email: メールアドレス
        phone_number: 電話番号

  time:
    formats:
        full_date: "%Y年%m月%d日 (%a)"
  views:
    pagination:
      first: "&laquo; 最初"
      last: "最後 &raquo;"
      previous: "&lsaquo; 前"
      next: "次 &rsaquo;"
      truncate: "..."
  helpers:
    page_entries_info:
      one_page:
        display_entries:
          zero: ""
          one: "<strong>1-1</strong>/1件中"
          other: "<strong>1-%{count}</strong>/%{count}件中"
      more_pages:
        display_entries: "<strong>%{first}-%{last}</strong>/%{total}件中"
  datetime:
    distance_in_words:
      half_a_minute: "30秒前後前"
      less_than_x_seconds:
        one:   "1秒前"
        other: "%{count}秒前"
      x_seconds:
        one:   "1秒"
        other: "%{count}秒前"
      less_than_x_minutes:
        one:   "1分"
        other: "%{count}分前"
      x_minutes:
        one:   "約1分前"
        other: "%{count}分前"
      about_x_hours:
        one:   "約1時間前"
        other: "約%{count}時間前"
      x_days:
        one:   "1日前"
        other: "%{count}日前"
      about_x_months:
        one:   "約1ヶ月前"
        other: "約%{count}ヶ月前"
      x_months:
        one:   "1ヶ月前"
        other: "%{count}ヶ月前"
      almost_x_years:
        one:   "1年弱前"
        other: "%{count}年弱前"
      about_x_years:
        one:   "約1年前"
        other: "約%{count}年前"
      over_x_years:
        one:   "1年以上前"
        other: "%{count}年以上前"        



↓↓クリックして頂けると励みになります。


[07]氏名認証<< [ホームに戻る] >> [09]Gメール