| 40 | 予約確認メール << [ホーム] >> | 42 | 通知
メッセージと会話のモデルを作成していきます。
コマンド
rails g model Conversation sender:references receiver:references
コマンド
rails g model Message content:text user:references conversation:references
「db\migrate\20200728232206_create_conversations.rb」ファイルを編集します。
記述更新 db\migrate\20200728232206_create_conversations.rb
コードをコピーしてファイルの内容を置き換えて下さい。
class CreateConversations < ActiveRecord::Migration[6.0] def change create_table :conversations do |t| t.references :sender, foreign_key: { to_table: :users } t.references :receiver, foreign_key: { to_table: :users } t.timestamps end end end
コマンド マイグレーション適用
rails db:migrate
「app\models\conversation.rb」ファイルを以下の記述に変更します。
記述変更 app\models\conversation.rb
class Conversation < ApplicationRecord belongs_to :sender, class_name: "User" belongs_to :receiver, class_name: "User" def last_message message = Message.where(conversation_id: self.id).last if message.present? return message else return Message.new updated_at: Time.now end end end
「app\models\message.rb」ファイルを以下の記述に変更します。
記述追加 app\models\message.rb
5行目に「validates :content, presence: { message: '空白にはできません' }」の記述を追加しています。
class Message < ApplicationRecord belongs_to :user belongs_to :conversation validates :content, presence: { message: '空白にはできません' } end
メッセージコントローラを作成します。
コマンド
rails g controller messages create
「app\controllers\messages_controller.rb」ファイルを以下のように変更します。
記述変更 app\controllers\messages_controller.rb
class MessagesController < ApplicationController def create if current_user.id == message_params[:receiver_id] redirect_to request.referrer, alert: "自分にメッセージを送ることはできません" end conversation = Conversation.where("(sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)", current_user.id, message_params[:receiver_id], message_params[:receiver_id], current_user.id ).first if !conversation.present? conversation = Conversation.create(sender_id: current_user.id, receiver_id: message_params[:receiver_id]) end @message = Message.new(user_id: current_user.id, conversation_id: conversation.id, content: message_params[:content] ) if @message.save redirect_to request.referrer, notice: "メッセージを送りました。" else redirect_to request.referrer, alert: "メッセージを送ることができません。" end end private def message_params params.require(:message).permit(:content, :receiver_id) end end
ビューの編集をします。
「app\views\users\show.html.erb」ファイルを以下のように編集します。
記述更新 app\views\users\show.html.erb
<div class="row" style="margin: 20px;"> <!-- 左側 --> <div class="col-4"> <div class="card"> <div class="card-body"> <!-- アバター --> <%= image_tag avatar_url(@user), class: "img-fluid img-thumbnail rounded-pill" %> <!-- ユーザー名 --> <div class="mx-auto" style="text-align: center;"> <h5 class="card-title btn-block"> <br/> <!-- オンラインステータス --> <span style="position:relative; top: 0.8rem; left: 0.5rem;"> <% if @user.status %> <span class="badge rounded-pill bg-success text-light">Online</span> <% else %> <span class="badge rounded-pill bg-secondary text-light">Offline</span> <% end %> </span> <%= @user.full_name %> </h5> <%= @user.about %> </div> <% if current_user.id != @user.id %> <!-- Button trigger modal --> <button type="button" class="btn btn-outline-primary btn-block" data-toggle="modal" data-target="#staticBackdrop"> <div class="mx-auto" style="width: 200px;">ホストにメッセージを送る send message to host</div> </button> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">メッセージ送信 Send Messege</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="row"> <div class="col-6"> <%= image_tag avatar_url(@user), class: "card-img-top rounded-pill", style: "width: 8rem;" %> <hr/> <strong>確認しましょう:</strong> <ul class="is-size-7" style="list-style:initial"> <li>宿泊日時</li> <li>宿泊場所</li> <li>設備</li> <li>キャンセルについて</li> </ul> </div> <div class="col-6"> <%= form_with model: Message.new do |f| %> <%= f.hidden_field :receiver_id, value: @user.id %> <%= f.text_area :content, class: "textarea", rows: 10, cols: 22 %> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button> <%= f.submit "ホストにメッセージを送る Send message to host", class: "btn btn-outline-primary btn-block" %> </div> <% end %> </div> </div> </div> <% else %> <!-- 画像アップロードボタン --> <a data-toggle="collapse" href="#collapseExample3" role="button" aria-expanded="false" aria-controls="collapseExample3" style="text-decoration: none;"> <div> <strong> <button type="button" class="btn btn-info btn-block"><i class="fas fa-upload"></i>アバター画像アップロード<br/> Avatar image upload</button> </strong> </a> <br/> <div class="collapse" id="collapseExample3"> <%= form_for :user, url: users_edit_url(current_user), action: :update, method: :post do |f| %> <%= f.file_field :avatar, class: "input-group-text", onchange: "this.form.submit();" %> <% end %> </div> <br/> </div> <% end %> <br/> <!-- 自己紹介 --> <div style="margin-left: 20px;"> <div class="collapse" id="collapseExample2"> <div class="card card-body" style="width: 16rem;"> <%= form_for :user, url: users_edit_url(current_user), action: :update, method: :post do |f| %> <%= f.text_area :about, autofocus: true, autocomplete: 'form'%> <br/> <br/> <%= f.submit "保存", class: "btn btn-outline-info" %> <% end %> </div> </div> <div class="mx-auto" style="margin-top: 1rem; text-align: right;"> <%= l(current_user.created_at, format: :long) %> </div> </div> </div> </div> </div> <!-- 右側 --> <div class="col-8"> <!-- お知らせ --> <div class="card"> <div class="card-header"> お知らせ </div> <div class="card-body"> <h5 class="card-title"></h5> <p class="card-text"></p> </div> </div> <br/> <!-- 登録しているお部屋 --> <div class="card"> <div class="card-header bg-dark text-light"> <%= @user.full_name %>さんが登録しているお部屋(<%= @rooms.length %>) </div> <div class="card-body"> <div class="row"> <% @user.rooms.each do |room| %> <% if room.active? %> <div class="col-6 col-md-4" style="margin-bottom: 20px;"> <%= link_to room_path(room), data: { turbolinks: false} do %> <%= image_tag room_cover(room), style: "width: 100%; height: 180;" %> <% end %> <span class="badge bg-light"><div id="star_<%= room.id %>"></div><i class="fa fa-star fa-1x" style="color: gold;"></i><span style="font-size: 1rem;"><%= pluralize(room.average_rating, "") %></span></span><br/> <%= link_to room.listing_name, room_path(room), data: { turbolinks: false}, class: "badge bg-info text-light" %><br/> <div class="badge bg-secondary text-light">住所:<%= room.address %></div><br/> <footer class="badge bg-warning" style="font-size: 0.9rem;"><%= number_to_currency(room.price) %></footer> </div> <% end %> <% end %> </div> </div> </div> <br/> <!-- レビュー --> <div class="card"> <div class="card-header bg-warning"> <%= @user.full_name %>さんへのレビュー </div> <div class="card-body"> <%= render "reviews/guest_list" %> <%= render "reviews/host_list" %> </div> </div> <br/> </div> </div>
ルートの設定をします。
3行目に自動で追加された「get 'messages/create'」の記述は削除して下さい。
記述追加 config\routes.rb
18行目に「post 'messages', to: 'messages#create'」の記述を追加しています。
Rails.application.routes.draw do # ルートを app\views\pages\home.html.erb に設定 root 'pages#home' 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 '/host_calendar' => "calendars#host" get 'settings/payment', to: 'users#payment', as: 'settings_payment' get 'settings/payout', to: 'users#payout', as: 'settings_payout' post '/users/edit', to: 'users#update' post '/settings/payment', to: 'users#update_payment', as: "update_payment" post 'messages', to: 'messages#create' devise_for :users, path: '', path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'}, controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'} 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] do member do post '/approve' => "reservations#approve" end end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
ブラウザ確認
http://localhost:3000/users/2
自分自身にはメッセージを送ることはできませんので、他のユーザにメッセージを送って確認します。
メッセージを送ります。
メッセージを送ることができました。
会話表示できるようにします。
「app\controllers」フォルダに「conversations_controller.rb」ファイルを新規作成して下さい。
app\controllers\conversations_controller.rb(新規作成したファイル)
class ConversationsController < ApplicationController before_action :get_conversations def list end def show @user = User.find(params[:id]) @conversation = Conversation.where("(sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)", current_user.id, params[:id], params[:id], current_user.id ).first if !@conversation.present? redirect_to conversations_path, alert: "無効です" else @messages = Message.where(conversation_id: @conversation.id) end end private def get_conversations @conversations = Conversation .where("sender_id = ? OR receiver_id = ?", current_user.id, current_user.id) .order(updated_at: :desc) end end
ルートの設定をします。
「config\routes.rb」ファイルに以下の記述を追加します。
記述追加 config\routes.rb(15,16行目)
get '/conversations', to: 'conversations#list', as: "conversations" get '/conversations/:id', to: 'conversations#show', as: "conversation_detail"
config\routes.rb
Rails.application.routes.draw do # ルートを app\views\pages\home.html.erb に設定 root 'pages#home' 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 '/host_calendar' => "calendars#host" 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" post '/users/edit', to: 'users#update' post '/settings/payment', to: 'users#update_payment', as: "update_payment" post 'messages', to: 'messages#create' devise_for :users, path: '', path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'}, controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'} 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] do member do post '/approve' => "reservations#approve" end end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
ナビゲーションバーにリンクを追加します。
記述追加 app\views\shared\_navbar.html.erb
61行目に「<%= link_to 'メッセージの確認', conversations_path, class: "btn btn-info", style: "margin-left: 0.5rem;", data: { turbolinks: false} %>」の記述を追加しています。
<nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="z-index: 5;"> <a class="navbar-brand" href="/"><h1 class="navh1"><font style="font-size: 1.2rem"><b>民泊予約サイト</font> <font style="font-size: 0.9rem">Private lodging reservation site</b></font></h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navbarNavDropdown"> <ul class="navbar-nav"> <!-- もしログインしていなかったら--> <% if (!user_signed_in?) %> <li class="nav-item" style="margin-right: 20px; margin-bottom: 5px;"> <%= link_to "まずはユーザ登録 Sign up", new_user_registration_path, class: "btn btn-danger btn-sm" %> </li> <li class="nav-item"> <%= link_to "ユーザ登録がお済みの方はこちら login", new_user_session_path, class: "btn btn-info btn-sm", style: "margin-right: 80px;" %> </li> <!-- ログインしていたら --> <% else %> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <figure style="position:relative; top: 0.2rem;" class="avatar <%= current_user.status ? "online" : "offline" %>"></figure> <%= image_tag avatar_url(current_user), class: "bd-placeholder-img figure-img img-fluid rounded-pill", style: "width: 40px; height: 30px; margin-top: 0.5rem;" %> <div class="btn btn-light bg-light text-dark"><%= current_user.full_name %></div> </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <span class="dropdown-item"><i class="fas fa-user-edit"></i> <%= link_to "ユーザ登録情報編集", edit_user_registration_path, class: "btn btn-warning" %></span> <span class="dropdown-item"><i class="fas fa-sign-out-alt"></i> <%= link_to "ログアウト", destroy_user_session_path, method: :delete, class: "btn btn-danger" %></span> </div> </li> <% end %> </ul> </div> </nav> <% if (user_signed_in?) %> <nav class="navbar navbar-expand-lg navbar-light bg-info" style="z-index: 3;"> <div class="collapse navbar-collapse justify-content-end" id="navbarNavDropdown"> <ul class="navbar-nav mr-auto"> <li class="nav-item" style="margin-top: 7px;"> <i class="fas fa-tachometer-alt" style="color: white;"></i> <%= link_to 'ダッシュボード Dashboard', dashboard_path, class: "btn btn-light" %> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-hospital-symbol" style="color: white;"></i> <div class="btn btn-light bg-light text-dark">ホスト Host</div> </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <span class="dropdown-item"><i class="fas fa-edit"></i></i><%= link_to "部屋を新規登録", new_room_path, class: "btn btn-primary", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> <span class="dropdown-item"><i class="far fa-list-alt"></i><%= link_to "部屋管理", rooms_path, class: "btn btn-success", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> <span class="dropdown-item"><i class="far fa-list-alt"></i><%= link_to "受注管理", your_reservations_path, class: "btn btn-danger", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> <span class="dropdown-item"><i class="far fa-list-alt"></i><%= link_to "カレンダー", host_calendar_path, class: "btn btn-warning", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> <span class="dropdown-item"><i class="far fa-credit-card"></i><%= link_to "支払い", settings_payout_path, class: "btn btn-info", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-user-friends" style="color: white;"></i> <div class="btn btn-light bg-light text-dark">ゲスト Guest</div> </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <span class="dropdown-item"><i class="far fa-list-alt"></i><%= link_to "ご予約の確認", your_trips_path, class: "btn btn-success", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> <span class="dropdown-item"><i class="far fa-credit-card"></i><%= link_to "クレジットカード", settings_payment_path, class: "btn btn-primary", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> <span class="dropdown-item"><i class="far fa-comment-dots fa-flip-horizontal"></i><%= link_to 'メッセージの確認', conversations_path, class: "btn btn-info", style: "margin-left: 0.5rem;", data: { turbolinks: false} %></span> </div> </li> </ul> </div> </nav> <% end %>
「app\views」フォルダに「conversations」フォルダを新規作成して下さい。
作成した「conversations」フォルダに「list.html.erb」ファイルを新規作成します。
app\views\conversations\list.html.erb(新規作成したファイル)
<div class="container"> <p class="menu-label badge bg-success text-light" style="margin-top: 3rem; font-size: 1.1rem;"> 会話を選択 Select conversation </p> <div class="row"> <div class="col-sm-4"> <ul class="menu-list" style="padding-left:0;"> <% @conversations.each do |c| %> <% @client = c.sender_id == current_user.id ? c.receiver : c.sender %> <%= link_to conversation_detail_path(@client.id), style: "text-decoration: none;" do %> <li style="list-style:none;"> <div class="card" style="width: 18rem;"> <div style="padding-left: 25px; padding-top: 15px;"><%= image_tag avatar_url(@client), class: "rounded-pill", style: "width: 5rem;" %></div> <div class="card-body"> <p class="card-text"> <span class="badge bg-secondary text-light"><%= @client.full_name %></span><br/> <div style="background-color: #f0fff0; border-radius: 0.5rem; padding: 1rem; color: black;"><%= (c.last_message.user_id == current_user.id ? "あなた: #{c.last_message.content}" : c.last_message.content).truncate(20) %></div><br/> <span class="badge bg-warning text-dark" style="position: relative; top: 1rem;"><%= I18n.l(c.last_message.updated_at, format: :full_date) %></span> </p> </div> </div> </li> <% end %> <% end %> </ul> </div> <div class="col-sm-8"> <p class="subtitle has-text-centered" style="margin-left: 3rem;"> 会話を選択して下さい Please select a conversation </p> </div> </div> </div>
「app\views\conversations」フォルダに「show.html.erb」ファイル新規作成してください。
app\views\conversations\show.html.erb(新規作成したファイル)
<section class="container" data-channel-subscribe="conversation" data-conversation-id="<%= @conversation.id %>" data-user-id="<%= current_user.id %>"> <div class="row"> <div class="col-md-4"> <nav class="nav"> <p class="menu-label badge bg-primary text-light" style="margin-top: 3rem; font-size: 1.1rem;"> 会話の内容 Conversation content </p> <ul class="menu-list" style="padding-left:0;"> <% @conversations.each do |c| %> <% @client = c.sender_id == current_user.id ? c.receiver : c.sender %> <%= link_to conversation_detail_path(@client.id), style: "text-decoration: none;" do %> <li style="list-style:none;"> <div class="card" style="width: 18rem;"> <div style="padding-left: 25px; padding-top: 15px;"><%= image_tag avatar_url(@client), class: "rounded-pill", style: "width: 5rem;" %></div> <div class="card-body"> <p class="card-text"> <span class="badge bg-secondary text-light"><%= @client.full_name %></span><br/> <div style="background-color: #f0ffff; border-radius: 0.5rem; padding: 1rem; color: black;"><%= (c.last_message.user_id == current_user.id ? "あなた: #{c.last_message.content}" : c.last_message.content).truncate(20) %></div><br/> <span class="badge bg-warning text-dark" style="position: relative; top: 1rem;"><%= I18n.l(c.last_message.updated_at, format: :full_date) %></span> </p> </div> </div> </li> <% end %> <% end %> </ul> </nav> </div> <div class="col-md-8"> <div style="width: 87%; margin-top: 2rem; margin-bottom: 2rem;"> <button class="btn btn-success btn-block" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> メッセージを送る send a message </button> </div> <div class="collapse" id="collapseExample"> <!-- メッセージを送る --> <div class="column m-t-25" style="margin-bottom: 3rem; margin-top: 2rem;"> <%= form_with model: Message.new, id: "new_message" do |f| %> <%= f.hidden_field :receiver_id, value: @user.id %> <%= f.text_area :content, class: "form-control form-control-lg", placeholder: "ここにメッセージを入力 Enter the message here", rows: 4 %> <br/> <%= f.submit "メッセージを送る send a message", class: "btn btn-outline-success btn-block rounded-pill" %> <% end %> </div> </div> <!-- メッセージ --> <div style="width: 160%;" id="message_list"> <% @messages.sort.reverse.each do |m| %> <%= render 'conversations/message', m: m, user: current_user %> <% end %> </div> </div> </div> </section>
「app\views\conversations」フォルダに「_message.html.erb」ファイル新規作成してください。
app\views\conversations\_message.html.erb(新規作成したファイル)
<% if m.user.id == user.id %> <div class="col-md-7"> <div style="margin-left: 20rem;"> <div style="margin-left: 1rem; margin-bottom: 0.5rem;"><%= image_tag avatar_url(m.user), class: "rounded-pill", style: "width: 3rem;" %></div> <div style="background-color: #afeeee; border-radius: 0.5rem; padding: 1rem;"><%= simple_format(m.content) %></div><br/> <span class="badge bg-info text-light" style="position: relative; left: 13rem; bottom: 3rem; font-size: 0.8rem;"><%= time_ago_in_words(m.created_at) %></span> </div> </div> <br/> <br/> <% else %> <div class="col-md-7" style="width: 30%;"> <div style="margin-left: 1rem; margin-bottom: 0.5rem;"><%= image_tag avatar_url(m.user), class: "rounded-pill", style: "width: 3rem;" %></div> <div style="background-color: #f0fff0; border-radius: 0.5rem; padding: 1rem;"><%= simple_format(m.content) %></div><br/> <span class="badge bg-success text-light" style="position: relative; left: 13rem; bottom: 3rem; font-size: 0.8rem;"><%= time_ago_in_words(m.created_at) %></span> </div> <br/> <% end %>
ブラウザ確認
http://localhost:3000/conversations
会話形式でメッセージを送ることができます。
↓↓クリックして頂けると励みになります。
| 40 | 予約確認メール << [ホーム] >> | 42 | 通知