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

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

Rails6.0 | 民泊予約サイトの構築 | 86 | Bootstrap | AJAX検索

[85]Bootstrap | ホームページ<< [ホームに戻る] >> [87]Bootstrap | jQueryスライダー


「37 | AJAX検索」をBootstrapの記述に書き換えます。
設定部分は省略します。


記述追加 app\controllers\pages_controller.rb
「search()」メソッドの実装

class PagesController < ApplicationController
  
  def home
      @rooms = Room.where(active: true).limit(3)
  end
  
  def search
    # ステップ 1
    if params[:search].present? && params[:search].strip != ""
      session[:loc_search] = params[:search]
    end
    arrResult = Array.new
    # ステップ 2
    if session[:loc_search] && session[:loc_search] != ""
      @rooms_address = Room.where(active: true).near(session[:loc_search], 5, order: 'distance')
    else
      @rooms_address = Room.where(active: true).all
    end
    # ステップ 3
    @search = @rooms_address.ransack(params[:q])
    @rooms = @search.result
    @arrRooms = @rooms.to_a
    # ステップ 4
    if (params[:start_date] && params[:end_date] && !params[:start_date].empty? &&  !params[:end_date].empty?)
      start_date = Date.parse(params[:start_date])
      end_date = Date.parse(params[:end_date])
      @rooms.each do |room|
        not_available = room.reservations.where(
          "(? <= start_date AND start_date <= ?)
          OR (? <= end_date AND end_date <= ?)
          OR (start_date < ? AND ? < end_date)",
          start_date, end_date,
          start_date, end_date,
          start_date, end_date
        ).limit(1)
        if not_available.length > 0
          @arrRooms.delete(room)
        end
      end
    end
  end

end



記述追加 config\routes.rb
「get 'search' => 'pages#search'」の記述を追加(16行目)

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: {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'
  
  post '/users/edit', to: 'users#update'

  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]

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end



記述更新 app\views\pages\home.html.erb

<%= form_tag search_path, method: :get, data: { turbolinks: false} do %>
  <div class="has-bg-img">

  <h2 style="color: white; padding-top: 200px; padding-left: 50px;">
  素敵なご旅行をあなたに <br>
  どんなお部屋をお探しですか?
</h2>

    <div class="row" style="padding: 50px;">

      <div class="col-md-6">
        <%= text_field_tag :search, params[:search], placeholder: "どちらのお部屋をおさがしですか?", class: "form-control" %>
      </div>
      <div class="col-md-3">
        <%= text_field_tag :start_date, params[:start_date], placeholder: "チェックイン", readonly: true, class: "form-control datepicker" %>
      </div>
      <div class="col-md-3">
        <%= text_field_tag :end_date, params[:end_date], placeholder: "チェックアウト", readonly: true, class: "form-control datepicker" %>
      </div>
    </div>

    <div class="row" style="padding-left: 50px; padding-bottom: 50px;">
      <div class="col-md-offset-4 col-md-4">
        <%= submit_tag "検索", class: "btn btn-danger btn-block" %>
      </div>
    </div>
  </div>
<% end %>
<br/><hr/><br/>
<!-- ホーム -->
<div style="margin-left: 50px;"><h3>お部屋</h3></div>
<br/>
<div class="row" style="margin: 50px;">
  <% @rooms.each do |room| %>
      <div class="col-md-4">

            <%= image_tag room_cover(room), style: "width: 100%; height: 180;" %>
 
            <%= link_to room.listing_name, room %>

      </div>
  <% end %>
</div>
<script>
  $('#start_date').datepicker({
    dateFormat: 'dd-mm-yy',
    minDate: 0,
    maxDate: '3m',
    onSelect: function(selected) {
      $('#end_date').datepicker("option", "minDate", selected);
      $('#end_date').attr("disabled", false);
    }
  });
  $('#end_date').datepicker({
    dateFormat: 'dd-mm-yy',
    minDate: 0,
    maxDate: '3m',
    onSelect: function(selected) {
      $('#start_date').datepicker("option", "maxDate", selected);
    }
  });
</script>



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


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

<div id="main">
  <div id="left" style="padding-left: 50px;">
    <!-- 検索パネル -->
    <div class="row">
      <br/>
      <div id="collapsePanel">
        <%= search_form_for @search, url: search_path, remote: true do |f| %>

              <div class="row">

                <div class="col-md-8">
                <label><i class="fas fa-yen-sign"></i>&nbsp;&nbsp;宿泊費(円)</label>
                <div id="slider-range" style="margin-top: 20px;"></div>
                </div>
                <div class="col-md-2">
                  <label>最低(円)</label>
                  <%= f.text_field :price_gteq, class: "form-control" %>
                </div>
                <div class="col-md-2">
                  <label>最高(円)</label>
                  <%= f.text_field :price_lteq, class: "form-control" %>
                </div>
              </div>
              <hr/>
              <div class="row">
                <div class="col-md-8">
                    <label><i class="far fa-calendar-alt"></i>&nbsp;&nbsp;宿泊日</label>
                </div>
                <div class="col-md-6">
                  <%= text_field_tag :start_date, params[:start_date], readonly: true, placeholder: "チェックイン日", class: "form-control datepicker" %>
                </div>
                <div class="col-md-6">
                  <%= text_field_tag :end_date, params[:end_date], readonly: true, placeholder: "チェックアウト日", class: "form-control datepicker" %>
                </div>
              </div>
              <hr/>
              <div class="row">
                <div class="col-md-4">
                  <%= check_box_tag "q[room_type_eq_any][]", "プライベート" %> プライベート
                </div>
                <div class="col-md-4">
                  <%= check_box_tag "q[room_type_eq_any][]", "シェア" %> シェア
                </div>
              </div>
              <hr/>
              <div class="row">
                <div class="col-md-4">
                  <div class="form-group select">
                    <label><i class="fas fa-user-friends"></i>&nbsp;宿泊人数</label>
                    <%= f.select :accommodate_gteq, [["2人", 2], ["3人", 3], ["4人", 4], ["5人", 5], ["6人", 6]], id: "accommodate", prompt: "選択してください", class: "form-control" %>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="form-group select">
                    <label><i class="fas fa-bed"></i>&nbsp;ベッド数</label>
                    <%= f.select :bed_room_gteq, [["1台", 1], ["2台", 2], ["3台", 3], ["4台", 4], ["5台", 5], ["6台", 6]], id: "bed_room", prompt: "選択してください", class: "form-control" %>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="form-group select">
                    <label><i class="fas fa-door-closed"></i>&nbsp;部屋数</label>
                    <%= f.select :bath_room_gteq, [["1部屋", 1], ["2部屋", 2], ["3部屋", 3], ["4部屋", 4], ["5部屋", 5], ["6部屋", 6]], id: "bath_rooms", prompt: "選択してください", class: "form-control" %>
                  </div>
                </div>
              </div>
              <hr/>
              <div class="row">
                <div class="col-md-4">
                  <%= check_box_tag "q[is_tv_eq]", true %> <i class="fas fa-tv"></i>&nbsp;テレビ
                </div>
                <div class="col-md-4">
                  <%= check_box_tag "q[is_kitchen_eq]", true %> <i class="fas fa-blender"></i>&nbsp;キッチン
                </div>
                <div class="col-md-4">
                  <%= check_box_tag "q[is_Internet_eq]", true %> <i class="fas fa-wifi"></i>&nbsp;インターネット
                </div>
                <div class="col-md-4">
                  <%= check_box_tag "q[is_heating_eq]", true %> <i class="fab fa-hotjar"></i>&nbsp;暖房
                </div>
                <div class="col-md-4">
                  <%= check_box_tag "q[is_air_eq]", true %> <i class="fas fa-temperature-low"></i>&nbsp;エアコン
                </div>
              </div>
              <hr/>
              <div class="row text-center">
                <%= f.submit "検索", class: "btn btn-primary btn-block" %>
              </div>
        <% end %>
      </div>
      <br/>
     <!-- お部屋 -->
      <div class="row" id="room_listing" style="margin-top: 50px;">
      <%= render partial: "rooms/rooms_list", locals: {rooms: @arrRooms} %>
  </div>



    </div>
  </div>

  <div id="right" style="width: 400px;">
    <!-- GOOGLEマップ -->
    <div id="map" style="width: 100%; height: 100%"></div>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script>
        function initialize(rooms) {
          var location = {lat: 43.061771, lng: 141.354451}
          if (rooms.length > 0) {
            location = {lat: rooms[0].latitude, lng: rooms[0].longitude}
          }
          var map = new google.maps.Map(document.getElementById('map'), {
            center: location,
            zoom: 12
          });
          var marker, inforwindow;
          rooms.forEach(function(room) {
            marker = new google.maps.Marker({
              position: {lat: room.latitude, lng: room.longitude},
              map: map
            });
            inforwindow = new google.maps.InfoWindow({
              content: "<div class='map_price'>" + room.price + "円</div>"
            });
            inforwindow.open(map, marker);
          })
        }
        google.maps.event.addDomListener(window, 'load', function() {
          initialize(<%= raw @arrRooms.to_json %>)
        });
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=ご自分のAPIキーを入れてください&callback=initMap" type="text/javascript"></script>
  </div>
</div>

<script>
  $('#start_date').datepicker({
    dateFormat: 'dd-mm-yy',
    minDate: 0,
    maxDate: '3m',
    onSelect: function(selected) {
      $('#end_date').datepicker("option", "minDate", selected);
      $('#end_date').attr("disabled", false);
    }
  });
  $('#end_date').datepicker({
    dateFormat: 'dd-mm-yy',
    minDate: 0,
    maxDate: '3m',
    onSelect: function(selected) {
      $('#start_date').datepicker("option", "maxDate", selected);
    }
  });
</script>

<script>
  $(function() {
    $("#q_price_gteq").val('1000');
    $("#q_price_lteq").val('15000');
    $("#slider-range").slider({
      range: true,
      min: 0,
      max: 15000,
      values: [1000, 15000],
      slide: function(event, ui) {
        $("#q_price_gteq").val(ui.values[0]);
        $("#q_price_lteq").val(ui.values[1]);
      }
    });
    $(".ui-widget-header").css('background', '#00A699');
    $(".ui-state-default, .ui-widget-content").css('background', 'white');
    $(".ui-state-default, .ui-widget-content").css('border-color', '#00A699');
  })
</script>



「app\views\rooms」フォルダに「_rooms_list.html.erb」ファイルを新規作成して下さい。


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

<% @arrRooms.each do |room| %>
    <div class="col-6 col-md-3">

          <%= image_tag room_cover(room), style: "width: 100%; height: 180;" %>

          <h5 class="card-title"><%= link_to room.listing_name, room, data: { turbolinks: false} %></h5>
          <%= room.home_type %> | ベッド<%= room.bed_room %><p class="subtitle is-6 m-b-5"><%= room.address %></p>
            <strong class="btn btn-danger btn-block disabled"><%= number_to_currency(room.price) %></strong>

    </div>

<% end %>



「app\views\pages」フォルダに「search.js.erb」ファイルを新規作成してください。


app\views\pages\search.js.erb(新規作成したファイル)

$('#room_listing').html('<%= j render partial: "rooms/rooms_list", locals: {rooms: @arrRooms} %>')
initialize(<%= raw @arrRooms.to_json %>)



ブラウザ確認
AJAX検索ができるようになりました。


http://localhost:3000/

検索画面
検索画面



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


[85]Bootstrap | ホームページ<< [ホームに戻る] >> [87]Bootstrap | jQueryスライダー

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

関連記事(外部サイト)