↓↓クリックして頂けると励みになります。
【44 | メッセージ】 << 【ホーム】 >> 【46 | ファイル添付コメント】
前のセクションで実装したメッセージをLINEのような会話形式で表示させます。
コントローラー
会話コントローラーを作成します。
「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
レンダービューを作成します。
「app\views」フォルダに「conversations」フォルダを新規作成して下さい。
作成した「app\views\conversations」フォルダに「_message.html.erb」ファイル新規作成してください。
app\views\conversations\_message.html.erb(新規作成したファイル)
<% if m.user.id == user.id %> <div class="col-md-6 mb-4" style="margin-right: auto;"> <div class="bg-success bg-opacity-25 p-1" style="border-radius: 8px;"> <%= image_tag avatar_url(m.user), class: "rounded-pill", style: "width: 2rem;" %> <span><%= m.user.full_name %></span> <div class="mt-4"><%= simple_format(m.content) %></div> <div class="text-secondary"><small><%= time_ago_in_words(m.created_at) %></small></div> </div> </div> <% else %> <div class="col-md-6 mb-4" style="margin-left: auto;"> <div class="bg-warning bg-opacity-25 p-1" style="border-radius: 8px;"> <%= image_tag avatar_url(m.user), class: "rounded-pill", style: "width: 2rem;" %> <span><%= m.user.full_name %></span> <%= simple_format(m.content) %> <div class="text-secondary"><small><%= time_ago_in_words(m.created_at) %></small></div> </div> </div> <% end %>
先ほど作成した「conversations」フォルダに「list.html.erb」ファイルを新規作成します。
app\views\conversations\list.html.erb(新規作成したファイル)
<div class="container mt-4"> <div class="row"> <p class="font2"> 会話を選択 </p> <div class="col-md-4"> <ul class="list-group"> <% @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 class="list-group-item" style="border: none;"> <div class="card"> <div class="card-body"> <%= image_tag avatar_url(@client), class: "rounded-pill", style: "width: 2rem;" %> <span class="font2"><%= @client.full_name %>との会話</span> <div class="mt-4 mb-3 font2"><%= (c.last_message.user_id == current_user.id ? " #{c.last_message.content}" : c.last_message.content).truncate(20) %></div> <div class="text-secondary"><small><%= I18n.l(c.last_message.updated_at, format: :full_date) %></small></div> </div> </div> </li> <% end %> <% end %> </ul> </div> <div class="col-sm-8"> <p class="font2"> ここに会話が表示されます。 </p> </div> </div> </div>
「app\views\conversations」フォルダに「show.html.erb」ファイル新規作成してください。
app\views\conversations\show.html.erb(新規作成したファイル)
<div 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"> <p class="font2"> 選択された会話 </p> <ul class="list-group"> <% @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 class="list-group-item" style="border: none;"> <div class="card"> <div class="card-body"> <%= image_tag avatar_url(@client), class: "rounded-pill", style: "width: 2rem;" %> <span class="font2"><%= @client.full_name %>との会話</span> <div class="mt-4 mb-2 font2"><%= (c.last_message.user_id == current_user.id ? "#{c.last_message.content}" : c.last_message.content).truncate(20) %></div><br/> <div class="text-secondary"><small><%= I18n.l(c.last_message.updated_at, format: :full_date) %></small></div> </div> </div> </li> <% end %> <% end %> </ul> </div> <div class="col-md-8"> <div class="container mt-2"> <button class="btn btn-outline-primary w-100" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> メッセージフォーム <i class="fa-solid fa-chevron-down"></i> </button> <div class="card mt-1"> <div class="card-body"> <div class="collapse" id="collapseExample"> <!-- メッセージを送る --> <%= 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: "ここにメッセージを入力", rows: 4 %> <div class="mt-4"> <%= f.submit "メッセージを送る", class: "btn btn-outline-danger w-100" %> </div> <% end %> </div> <!-- メッセージ --> <div class="container"> <div class="row"> <div id="message_list" class="mt-4"> <% @messages.sort.reverse.each do |m| %> <%= render 'conversations/message', m: m, user: current_user %> <% end %> </div> </div> </div> </div> </div> </div> </div> </div> </div>
ルートの設定をします。
「config\routes.rb」ファイルに以下の記述を追加します。
記述追加 config\routes.rb(19,20行目)
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 get 'pages/home' get '/dashboard', to: 'users#dashboard' get '/users/:id', to: 'users#show', as: 'user' get '/selling_orders', to: 'orders#selling_orders' get '/buying_orders', to: 'orders#buying_orders' get '/all_requests', to: 'requests#list' get '/request_offers/:id', to: 'requests#offers', as: 'request_offers' get '/my_offers', to: 'requests#my_offers' get '/search', to: 'pages#search' get 'settings/payment', to: 'users#payment', as: 'settings_payment' get 'settings/payout', to: 'users#payout', as: 'settings_payout' get '/gigs/:id/checkout/:pricing_type', to: 'gigs#checkout', as: 'checkout' get '/conversations', to: 'conversations#list', as: "conversations" get '/conversations/:id', to: 'conversations#show', as: "conversation_detail" # post post '/users/edit', to: 'users#update' post '/offers', to: 'offers#create' post '/reviews', to: 'reviews#create' post '/search', to: 'pages#search' post '/settings/payment', to: 'users#update_payment', as: "update_payment" post 'messages', to: 'messages#create' # put put '/orders/:id/complete', to: 'orders#complete', as: 'complete_order' put '/offers/:id/accept', to: 'offers#accept', as: 'accept_offer' put '/offers/:id/reject', to: 'offers#reject', as: 'reject_offer' resources :gigs do member do delete :delete_photo post :upload_photo end resources :orders, only: [:create] end resources :requests resources :reviews, only: [:create, :destroy] # device devise_for :users, path: '', path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'}, controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'} # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. get "up" => "rails/health#show", as: :rails_health_check # Defines the root path route ("/") # root "posts#index" end
動作を確認します。
ゲストからホストにメッセージを送っておく必要があります。
ブラウザ確認
http://localhost:3000/conversations
LINEのように会話形式でメッセージを送ることができます。
ナビゲーションバーにリンクを追加します。
記述追加 app\views\shared\_navbar.html.erb
36行目に以下の記述を追加します。
<li><%= link_to "メッセージ", conversations_path, class: "dropdown-item btn btn-light", data: { turbo: false} %></li>
記述追加 app\views\shared\_navbar.html.erb
<nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <a class="navbar-brand" href="/" ><span class="font1">Gig Hub7</span></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <!-- もしログインしていなかったら--> <% if (!user_signed_in?) %> <li class="nav-item" style="margin-bottom: 0.1rem;"> <span style="margin-left: 1rem;"> <%= link_to "新規登録", new_user_registration_path, class: "btn btn-danger" %> </span> </li> <li class="nav-item"> <span style="margin-left: 1rem;"> <%= link_to "ログイン", new_user_session_path, class: "btn btn-success text-light" %> </span> </li> </ul> <!-- ログインしていたら --> <% else %> <ul class="navbar-nav" style="margin-left: 2rem;"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" 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;" %> <%= current_user.full_name %> </a> <ul class="dropdown-menu"> <li><%= link_to "ダッシュボード", dashboard_path, class: "dropdown-item btn btn-lightt" %></li> <li><%= link_to "ユーザ登録情報編集", edit_user_registration_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "リクエスト", all_requests_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "メッセージ", conversations_path, class: "dropdown-item btn btn-light", data: { turbo: false} %></li> <li><hr class="dropdown-divider"><span class="badge bg-danger" style="margin-left: 1rem;">フリーランサー</span></li> <li><%= link_to "仕事を新規登録", new_gig_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "仕事確認", selling_orders_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "申し込み確認", my_offers_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "振込口座登録", settings_payout_path, class: "dropdown-item btn btn-light", data: { turbo: false} %> <li><hr class="dropdown-divider"><span class="badge bg-primary" style="margin-left: 1rem;">クライアント</span></li> <li><%= link_to "依頼確認", buying_orders_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "リクエスト登録", new_request_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "リクエスト確認", requests_path, class: "dropdown-item btn btn-light" %></li> <li><%= link_to "クレジットカード登録", settings_payment_path, class: "dropdown-item btn btn-light", data: { turbo: false} %></li> <li><hr class="dropdown-divider"></li> <li><%= button_to "ログアウト", destroy_user_session_path, method: :delete, class: "dropdown-item btn btn-light" %></li> </ul> </li> </ul> <% end %> </div> </div> </nav>
ブラウザを確認します。
ドロップダウンに「メッセージ」のリンクが追加されています。
【44 | メッセージ】 << 【ホーム】 >> 【46 | ファイル添付コメント】
↓↓クリックして頂けると励みになります。