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

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

Rails6.0 | 民泊予約サイトの構築 | 50 | 通知

[49]メッセージと会話 | リアルタイムメッセージ<< [ホームに戻る] >> [51]フルカレンダー


コマンド
rails g model Notification content user:references


コマンド
rails g migration AddUnreadToUser unread:bigint


記述追加 db\migrate\20200729003608_add_unread_to_user.rb
3行目末尾に「, default: true」の記述追加

class AddUnreadToUser < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :unread, :bigint, default: true
  end
end



コマンド マイグレーション
rails db:migrate


記述追加 app\models\user.rb
7行目に「has_many :notifications」の記述追加

class User < ApplicationRecord

  has_many :rooms
  has_many :reservations
  has_many :guest_reviews, class_name: "GuestReview", foreign_key: "guest_id"
  has_many :host_reviews, class_name: "HostReview", foreign_key: "host_id"
  has_many :notifications

  has_one_attached :avatar

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable, :omniauthable

  validates :full_name, presence: true, length: {maximum: 50}      

  def is_active_host
    !self.merchant_id.blank?
  end

  def self.from_omniauth(auth)
    user = User.where(email: auth.info.email).first
    if user
      if !user.provider
        user.update(uid: auth.uid, provider: auth.provider, image: auth.info.image)
      end      
      return user
    else
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.email = auth.info.email
        user.password = Devise.friendly_token[0, 20]
        user.full_name = auth.info.name   # ユーザーモデルに名前があると仮定
        user.image = auth.info.image # ユーザーモデルに画像があると仮定
        user.uid = auth.uid
        user.provider = auth.provider
      end
    end
  end
  
end



記述追加 app\models\notification.rb
2行目に「after_create_commit { NotificationJob.perform_later self }」の記述追加

class Notification < ApplicationRecord
  after_create_commit { NotificationJob.perform_later self }
  belongs_to :user
end





「app\models\message.rb」ファイルを以下のように編集します。


1.6行目に以下の記述を追加します。

after_create_commit :create_notification



2.10行目に以下の記述を追加します。

  private
  def create_notification
    if self.conversation.sender_id == self.user_id
      sender = User.find(self.conversation.sender_id)
      Notification.create(content: "#{sender.full_name}から新しいメッセージがあります。", user_id: self.conversation.receiver_id)
    else
      sender = User.find(self.conversation.receiver_id)
      Notification.create(content: "#{sender.full_name}から新しいメッセージがあります。", user_id: self.conversation.sender_id)
    end
  end  



app\models\message.rb

class Message < ApplicationRecord

  belongs_to :user
  belongs_to :conversation

  after_create_commit :create_notification

  validates :content, presence: { message: '空白にはできません' }

  private
  def create_notification
    if self.conversation.sender_id == self.user_id
      sender = User.find(self.conversation.sender_id)
      Notification.create(content: "#{sender.full_name}から新しいメッセージがあります。", user_id: self.conversation.receiver_id)
    else
      sender = User.find(self.conversation.receiver_id)
      Notification.create(content: "#{sender.full_name}から新しいメッセージがあります。", user_id: self.conversation.sender_id)
    end
  end  

end



「app\models\reservation.rb」ファイルを以下のように編集します。


1.6行目に以下の記述を追加します

after_create_commit :create_notification



2.13行目に以下の記述を追加します。

  private
  def create_notification
    type = self.room.Instant? ? "新規予約" : "承認待ち"
    guest = User.find(self.user_id)
    Notification.create(content: "#{guest.full_name}様から#{type}のリクエストがあります。", user_id: self.room.user_id)
  end



app\models\reservation.rb

class Reservation < ApplicationRecord

  #    status: {承認待ち: 0, 承認: 1, 不承認: 2}
  enum status: {Waiting: 0, Approved: 1, Declined: 2}

  after_create_commit :create_notification

  belongs_to :user
  belongs_to :room

  has_many :reviews

  private
  def create_notification
    type = self.room.Instant? ? "新規予約" : "承認待ち"
    guest = User.find(self.user_id)
    Notification.create(content: "#{guest.full_name}様から#{type}のリクエストがあります。", user_id: self.room.user_id)
  end

end



「app\controllers」フォルダに「notifications_controller.rb」ファイルを新規作成して下さい。


app\controllers\notifications_controller.rb(新規作成したファイル)

class NotificationsController < ApplicationController
    before_action :authenticate_user!
  
    def index
      current_user.unread = 0
      current_user.save
      @notifications = current_user.notifications.order(created_at: "DESC").page(params[:page]).per(5)
    end
  end



コマンド
rails g channel notifications


「app\javascript\channels」フォルダに「notifications.coffee」ファイルを新規作成してください。


app\javascript\channels\notifications.coffee(新規作成したファイル)

$(() ->
  App.notifications = App.cable.subscriptions.create {channel: "NotificationsChannel", id: $('#user_id').val() },
    received: (data) ->
      $('#num_of_unread').html(data.unread)
      $('#notifications').prepend(data.message)
      $('#navbar_num_of_unread').html(data.unread)
)



書き換え app\channels\notifications_channel.rb

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "notification_#{params[:id]}"
  end
end



コマンド
rails g job notification


書き換え app\jobs\notification_job.rb

class NotificationJob < ApplicationJob
  queue_as :default

  def perform(notification)
    notification.user.increment!(:unread)
    ActionCable.server.broadcast "notification_#{notification.user.id}", message: render_notification(notification), unread: notification.user.unread
  end

  private

    def render_notification(notification)
      ApplicationController.render(partial: 'notifications/notification', locals: { notification: notification})
    end
end



記述追加 config\routes.rb
23行目に「get '/notifications' => 'notifications#index'」の記述追加

Rails.application.routes.draw do

  # ルートを app\views\pages\home.html.erb に設定
  root 'pages#home'

  mount ActionCable.server => '/cable'

  devise_for :users, 
              path: '', 
              path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'},
              controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}

  get 'pages/home'
  get '/dashboard', to: 'users#dashboard'
  get '/users/:id', to: 'users#show', as: 'user'
  get '/your_trips' => 'reservations#your_trips'
  get '/your_reservations' => 'reservations#your_reservations'
  get 'search' => 'pages#search'
  get 'settings/payment', to: 'users#payment', as: 'settings_payment'
  get 'settings/payout', to: 'users#payout', as: 'settings_payout'
  get '/conversations', to: 'conversations#list', as: "conversations"
  get '/conversations/:id', to: 'conversations#show', as: "conversation_detail"
  get '/notifications' => 'notifications#index'
  
  post '/users/edit', to: 'users#update'
  post '/settings/payment', to: 'users#update_payment', as: "update_payment"
  post 'messages', to: 'messages#create'

  resources :rooms, except: [:edit] do
    member do
      get 'listing'
      get 'pricing'
      get 'description'
      get 'photo_upload'
      get 'amenities'
      get 'location'
      get 'preload'
      get 'preview'
      delete :delete_photo
      post :upload_photo
    end
    resources :reservations, only: [:create]
  end

  resources :guest_reviews, only: [:create, :destroy]
  resources :host_reviews, only: [:create, :destroy]

  resources :reservations, only: [:approve, :decline] do
    member do
      post '/approve' => "reservations#approve"
      post '/decline' => "reservations#decline"
    end
  end
  
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end



「app\views」フォルダに「notifications」フォルダを新規作成してください。
作成した「notifications」フォルダに「index.html.erb」ファイルを新規作成します。



app\views\notifications\index.html.erb(新規作成したファイル)

<section class="section">
    <div class="container">

        <div style="margin-left: 50px; margin-bottom: 30px;">
            <%= link_to 'メッセージを見る', conversations_path, class: "button is-primary" %>
        </div>

        <table class="table" style="margin-left: 50px; margin-bottom: 50px;">

            <div class="container" id="notifications">

                <% @notifications.each do |n| %>

                    <tr>
                        <td>
                            <strong><%= n.content %></strong>
                            <span class="pull-right"><%= time_ago_in_words(n.created_at) %>&nbsp;&nbsp;&nbsp;(&nbsp;<%= n.created_at.strftime('%Y年%-m月%-d日 %-H時%-M分') %>&nbsp;)&nbsp;</span>
                        </td>
                    </tr>

                <% end %>

            </div>

        </table>

        <!-- ページネーション -->
        <div class="card">
            <div class="card-header-title is-centered">
                <%= paginate @notifications %>
            </div>
        </div>

    </div>
</section>



ダッシュボードビューを更新します。


記述追加 app\views\users\dashboard.html.erb(12行目)

<!--通知 -->
<article class="media">
    <div class="content" style="margin-left: 30px; margin-bottom: 10px;">
        <%= link_to notifications_path do %>
            <span id="num_of_unread"><%= current_user.unread %></span> 件の通知があります。
        <% end %>
    </div>
</article>



app\views\users\dashboard.html.erb

<section class="section">
    <div class="container">
        <div class="columns">
        
            <!-- 左パネル -->
            <div class="column is-one-third">
                <div class="columns is-multiline">
                
                    <!-- 上部 -->
                    <div class="column is-full">

                        <!--通知 -->
                        <article class="media">
                            <div class="content" style="margin-left: 30px; margin-bottom: 10px;">
                                <%= link_to notifications_path do %>
                                    <span id="num_of_unread"><%= current_user.unread %></span> 件の通知があります。
                                <% end %>
                            </div>
                        </article>                    

                        <div class="card">

                            <!-- アバター -->
                            <div class="card-content is-horizontal-center is-flex">
                                <figure class="image is-256x256">
                                    <%= image_tag avatar_url(current_user), class: "is-rounded" %>
                                </figure>
                            </div>
                            
                            <div class="card-content">
                                <!-- 画像アップロードボタン -->
                                <div class="content has-text-centered">
                                    <p class="title is-5">
                                        <%= current_user.full_name %>
                                    </p>
                                    <%= form_for :user, url: users_edit_url(@user), action: :update, method: :post do |f| %>
                                        <div class="file">
                                            <label class="button is-primary is-outlined is-fullwidth">
                                                <%= f.file_field :avatar, class: "file-input", onchange: "this.form.submit();" %>
                                                <i class="fas fa-upload"></i>&nbsp;&nbsp;&nbsp; アバター画像アップロード
                                            </label>
                                        </div>
                                    <% end %>                                       
                                </div>
                                <hr class="h-10">
                                
                                <!-- アカウント情報 -->
                                <article class="media">
                                    <div class="media-content">アカウント登録日</div>
                                    <div class="media-right">
                                        <strong><%= I18n.l(current_user.created_at, format: :full_date) %></strong>
                                    </div>
                                </article>
                                <hr class="h-10">
                                
                                <!-- オンラインステータス -->
                                <article>
                                    <div class="media">
                                        <div class="media-content">ステータス</div>
                                        <div class="media-right">
                                            <strong><% if current_user.status %> オンライン <% else %> オフライン <% end %></strong> <i class="toggle far fa-edit" aria-controls="user-status"></i>
                                        </div>
                                    </div>
                                    <div class="content">
                                        <%= form_for :user, url: users_edit_url(@user), action: :update, method: :post, html: {id: 'user-status', class: 'is-hidden'} do |f| %>
                                            <div class="field">
                                                <%= f.select(:status, options_for_select([["オンライン", true], ["オフライン", false]]), {}, {class: "select is-fullwidth"}) %>
                                            </div>
                                            <a class="toggle button is-light" aria-controls="user-status">キャンセル</a>
                                            <%= f.submit "保存", class: "button is-danger" %>
                                        <% end %>
                                    </div>
                                </article>
                            </div>
                        </div>
                    </div>

                    <!-- 下部 -->
                    <div class="column is-full">
                        <div class="card">

                            <div class="card-content">
                                <!-- アカウント詳細 -->
                                <article>
                                    <div class="media">
                                        <div class="media-content">
                                            <p>
                                                <strong>自己紹介</strong>
                                                <br>
                                                <%= current_user.about %>
                                            </p>
                                        </div>
                                        <div class="media-right">
                                            <i class="toggle far fa-edit" aria-controls="user-about"></i>
                                        </div>
                                    </div>
                                    <div class="content">
                                        <%= form_for :user, url: users_edit_url(@user), action: :update, method: :post, html: {id: 'user-about', class: 'is-hidden'} do |f| %>
                                            <div class="field">
                                                <%= f.text_area :about, autofocus: true, autocomplete: 'form', class: 'input'%>
                                            </div>
                                            <a class="toggle button is-light" aria-controls="user-about">キャンセル</a>
                                            <%= f.submit "保存", class: "button is-danger" %>
                                        <% end %>
                                    </div>
                                </article>
                                <hr class="h-10">
                                
                                <!-- 電話番号 -->
                                <article class="media">
                                    <% if !current_user.phone_number.blank? %>
                                    <span class="pull-right icon-babu"><i class="far fa-check-circle" style="color:#528fff;"></i></span>&nbsp;&nbsp;電話番号
                                    <% end %>                                
                                </article>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右側 -->
            <div class="column">
                <div class="columns is-multiline">
                
                    <!-- お部屋を登録する -->
                    <div class="column is-one-third has-text-centered">
                        <%= link_to new_room_path do %>
                            <div class="card">
                                <div class="card-image card-content is-horizontal-center is-flex ">
                                    <figure class="image is-256x256 ">
                                        <%= image_tag 'icon_add.png' %>
                                    </figure>
                                </div>
                                <div class="card-content">
                                    <strong>お部屋を新規登録する</strong>
                                </div>    
                            </div>
                        <% end %>
                    </div>
                    <!-- 登録したお部屋 -->
                    <% current_user.rooms.each do |room| %>
                        <% if room.active? %>
                            <div class="column is-one-third">
                                <div class="card">
                                    <div class="card-image">
                                        <%= link_to listing_room_path(room) do %>
                                            <figure class="image is-4by3">
                                                <%= image_tag room_cover(room) %>
                                            </figure>
                                        <% end %>
                                    </div>
                                    <br/>
                                    <div class="card-content p-t-5 p-b-5">
                                        <p class="subtitle is-6 m-b-5"><%= link_to room.listing_name, room_path(room), data: { turbolinks: false} %></p>
                                        <p class="subtitle is-6 m-b-5"><%= room.address %></p>
                                        <!--レビュー -->
                                    </div>
                                    <footer class="card-footer">
                                        <a class="has-text-danger is-block card-footer-item has-text-right">
                                            <span class="small-title">1泊の宿泊価格</span> 
                                            <strong><%= number_to_currency(room.price) %></strong>                                            
                                        </a>
                                    </footer>
                                </div>
                            </div>
                        <% end %>
                    <% end %>
                    
                </div>
            </div>
            
        </div>
    </div>
</section>



「app\views\layouts\application.html.erb」ファイルを編集します。


記述追加 app\views\layouts\application.html.erb(29行目)

    <% if current_user %>
        <input type="hidden" id="user_id" value="<%= current_user.id %>">
    <% end %>



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' %>
    <!-- Googleフォント -->
    <link href="https://fonts.googleapis.com/css2?family=Kosugi+Maru&display=swap" rel="stylesheet">
    <!-- アイコン Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <!-- 日付ピッカー デザインsunny-->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/sunny/jquery-ui.css">
    <!-- 日付ピッカーの日本語化-->
    <script src="https://rawgit.com/jquery/jquery-ui/master/ui/i18n/datepicker-ja.js"></script>

  </head>

  <body>

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

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

    <!-- 通知用 -->
    <% if current_user %>
        <input type="hidden" id="user_id" value="<%= current_user.id %>">
    <% end %>

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



ナビゲーションバーを更新します。


記述追加 app\views\shared\_navbar.html.erb(34行目)

<!-- 通知 -->
<div style="position: relative; top: 15px; left: -35px;">
    <%= link_to notifications_path do %>
        <i class="fa fa-bell fa-2x icon-babu"></i>

        <%if current_user.unread > 0 %>
            <span class="badge" id="navbar_num_of_unread"><%= current_user.unread %></span>
        <% end %>

    <% end %>
</div>



app\views\shared\_navbar.html.erb

<nav class="navbar is-light" role="navigation" aria-label="main navigation">
    <div class="navbar-brand">
        <a class="navbar-item" href="/">
            <h1>テストサイトMinpaku6</h1>
        </a>
        <a role="button" class="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample">
            <span aria-hidden="true"></span>
            <span aria-hidden="true"></span>
            <span aria-hidden="true"></span>
        </a>
    </div>
    
    <div id="navbarBasicExample" class="navbar-menu">
        <div class="navbar-start">
            <div class="navbar-item">
            </div>
        </div>
        <div class="navbar-end">
            <a class="navbar-item"></a>
            <a class="navbar-item"></a>

            <!-- もしログインしていなかったら-->
            <% if (!user_signed_in?) %>
                <div class="navbar-item">
                    <div class="buttons">
                        <%= link_to  "新規ユーザ登録", new_user_registration_path, class: "button is-white" %>
                        <%= link_to  "ログイン", new_user_session_path, class: "button is-white" %>
                    </div>
                </div>

            <!-- ログインしていたら -->
            <% else %>

                <!-- 通知 -->
                <div style="position: relative; top: 15px; left: -35px;">
                    <%= link_to notifications_path do %>
                        <i class="fa fa-bell fa-2x icon-babu"></i>
                        <%if current_user.unread > 0 %>
                            <span class="badge" id="navbar_num_of_unread"><%= current_user.unread %></span>
                        <% end %>
                    <% end %>
                </div>

                <div class="navbar-item has-dropdown is-hoverable" style="margin-right: 100px;">
                    <a class="navbar-item">
                        <figure class="image is-48x48 m-r-5 avatar <%= current_user.status ? "online" : "offline" %>">
                        <div style="margin-top: 0.6rem;">
                        <%= image_tag avatar_url(current_user), class: "is-rounded" %>
                        </div>
                        </figure>                    
                        <%= current_user.full_name %>
                    </a>
                    <div class="navbar-dropdown">
                        <%= link_to  "ユーザ登録情報編集", edit_user_registration_path, class: "navbar-item" %>
                        <a href="" class="navbar-item"></a>
                        <hr class="navbar-divider">
                        <%= link_to  "ログアウト", destroy_user_session_path, method: :delete, class: "navbar-item" %>
                    </div>
                </div>
            <% end %>            
        </div>
    </div>
</nav>

<% if (user_signed_in?) %>
    <nav class="navbar has-shadow" style="z-index: 3;">
        <div class="container">
            <div class="navbar">
                <%= link_to 'ダッシュボード', dashboard_path, class: "navbar-item" %>
                <%= link_to 'メッセージの確認', conversations_path, class: "navbar-item", data: { turbolinks: false} %>
                <div class="navbar-item has-dropdown is-hoverable">
                    <a class="navbar-link">ホスト</a>
                    <div class="navbar-dropdown">
                        <%= link_to  "お部屋を新規登録", new_room_path, class: "navbar-item" %>
                        <%= link_to  "登録したお部屋一覧", rooms_path, class: "navbar-item" %>
                        <%= link_to "受注予約の管理", your_reservations_path, class: "navbar-item" %>
                        <%= link_to '振込口座の登録', settings_payout_path, class: "navbar-item" %>
                    </div>
                </div>
                <div class="navbar-item has-dropdown is-hoverable">
                    <a class="navbar-link">ゲスト</a>
                    <div class="navbar-dropdown">
                        <%= link_to "ご予約の確認", your_trips_path, class: "navbar-item" %>
                        
                    </div>
                </div>
            </div>
        </div>
    </nav>
<% end %>

<script>
    $(document).ready(function() {
    // navbar burgerアイコンでクリックイベントを確認する
    $(".navbar-burger").click(function() {
        // 「navbar-burger」と「navbar-menu」の両方で「is-active」クラスを切り替える
        $(".navbar-burger").toggleClass("is-active");
        $(".navbar-menu").toggleClass("is-active");
    });
    });
</script>



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


何かアクションがあると通知がきてわかるようになりました。

通知の表示
通知の表示
通知の一覧
通知の一覧



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


[49]メッセージと会話 | リアルタイムメッセージ<< [ホームに戻る] >> [51]フルカレンダー