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

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

【民泊6.0】【MacOSX】会話

会話表示できるようにします。


「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(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'

  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"
  
  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\shared\_navbar.html.erb
59行目に「<%= link_to 'メッセージの確認', conversations_path, class: "navbar-item", data: { turbolinks: false} %>」の記述を追加しています。

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



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



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

<section class="section">
    <div class="columns">
    
        <div class="column is-4">
            <nav class="menu">
                <p class="menu-label">
                    全ての会話
                </p>
                <ul class="menu-list">
                    <% @conversations.each do |c| %>
                        <% @client = c.sender_id == current_user.id ? c.receiver : c.sender %>
                        <%= link_to conversation_detail_path(@client.id) do %>
                            <li>
                                <article class="message">
                                    <div class="message-body">
                                        <div class="media">
                                            <div class="media-left">
                                                <figure class="image is-32x32 m-r-5 avatar online">
                                                    <%= image_tag avatar_url(@client), class: "is-rounded" %>
                                                </figure>
                                            </div>                                
                                            <div class="media-content">
                                                <p class="title is-6"><%= @client.full_name %></p>
                                                <p class="subtitle is-7">
                                                    <%= (c.last_message.user_id == current_user.id ? "あなた: #{c.last_message.content}" : c.last_message.content).truncate(20) %>
                                                </p>
                                            </div>
                                            <div class="media-right">
                                                <p class="subtitle is-7"><%= I18n.l(c.last_message.updated_at, format: :full_date) %></p>
                                            </div>
                                        </div>
                                    </div>
                                </article>                    
                            </li>
                        <% end %>
                    <% end %>
                </ul>
            </nav>
        </div>

        <div class="column is-8">
            <section class="hero">
                <div class="hero-body">
                    <p class="subtitle has-text-centered">
                        会話を選択して下さい
                    </p>
                </div>
            </section>
        </div>
    </div>
</section>



「app\views\conversations」フォルダに「show.html.erb」ファイル新規作成してください。


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

<section class="section" data-channel-subscribe="conversation" data-conversation-id="<%= @conversation.id %>" data-user-id="<%= current_user.id %>">
    <div class="columns">
    
        <div class="column is-4">
            <nav class="menu">
                <p class="menu-label">
                    全ての会話
                </p>
                <ul class="menu-list">
                    <% @conversations.each do |c| %>
                        <% @client = c.sender_id == current_user.id ? c.receiver : c.sender %>
                        <%= link_to conversation_detail_path(@client.id) do %>
                            <li>
                                <article class="message <%= 'is-primary' if c.id == @conversation.id %>">
                                    <div class="message-body">
                                        <div class="media">
                                            <div class="media-left">
                                                <figure class="image is-32x32 m-r-5 avatar online">
                                                    <%= image_tag avatar_url(@client), class: "is-rounded" %>
                                                </figure>
                                            </div>                                
                                            <div class="media-content">
                                                <p class="title is-6"><%= @client.full_name %></p>
                                                <p class="subtitle is-7">
                                                    <%= (c.last_message.user_id == current_user.id ? "あなた: #{c.last_message.content}" : c.last_message.content).truncate(20) %>
                                                </p>
                                            </div>
                                            <div class="media-right">
                                                <p class="subtitle is-7"><%= I18n.l(c.last_message.updated_at, format: :full_date) %></p>
                                            </div>
                                        </div>
                                    </div>
                                </article>                    
                            </li>
                        <% end %>
                    <% end %>
                </ul>
            </nav>
        </div>
        <div class="column is-8">
            
            <!-- メッセージを受けた人  -->
            <article class="media">
                <div class="media-left">
                    <figure class="image is-64x64">
                        <%= image_tag avatar_url(@user), class: "is-rounded" %>
                    </figure>
                </div>
                <div class="media-content">
                    <div class="content">
                        <h3><%= @user.full_name %></h3>
                    </div>
                </div>
            </article>
            <hr>
            <!-- メッセージ  -->
            <div class="columns is-multiline" id="message_list">
                <% @messages.each do |m| %>
                    <%= render 'conversations/message', m: m, user: current_user %>
                <% end %>
            </div>
            <!-- メッセージを送る  -->
            <div class="column m-t-25">
                <%= form_with model: Message.new, id: "new_message" do |f| %>
                    <%= f.hidden_field :receiver_id, value: @user.id %>
                    <div class="field has-addons">
                        <div class="control" style="width: 100%">
                            <%= f.text_field :content, class: "input", placeholder: "メッセージを入力してください" %>
                        </div>
                        <div class="control">
                            <%= f.submit "メッセージを送る", class: "button is-primary" %>
                        </div>
                    </div>
                <% 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="column is-7 is-offset-5">
        <p class="notification is-primary conversation-message">
            <%= m.content %>
        </p>
        <span class="subtitle is-7"><%= time_ago_in_words(m.created_at) %></span>
    </div>
<% else %>
    <div class="column is-7">
        <article class="media">
            <div class="media-left">
                <figure class="image is-32x32">
                    <%= image_tag avatar_url(m.user), class: "is-rounded" %>
                </figure>
            </div>
            <div class="media-content">
                <p class="notification conversation-message">
                    <%= m.content %>
                </p>
                <span class="subtitle is-7"><%= time_ago_in_words(m.created_at) %></span>
            </div>
        </article>
    </div>
<% end %>



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


会話形式でメッセージを送ることができます。

会話
会話


YAE C5 CLINIC(札幌美容クリニック)

関連記事(外部サイト)