| 33 |レビューの実装 << [ホーム] >> | 35 |フルカレンダーの実装
「app\assets\images」フォルダに「home」フォルダを新規作成してください。作成した「home」フォルダの中に何でも良いのでホームページの背景画像となる「background01.jpg」ファイルをコピーして下さい。
app\controllers\pages_controller.rb
class PagesController < ApplicationController def home @rooms = Room.where(active: true).limit(3) end def search end end
app\views\pages\home.html.erb
<div class="has-bg-img"> <h2 style="color: cornsilk; 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 "検索 search", class: "btn btn-danger btn-block" %> </div> </div> </div> <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"> <%= link_to room_path(room), data: { turbolinks: false} do %> <%= image_tag room_cover(room), style: "width: 100%; height: 180;" %> <span class="badge bg-info text-light" style="font-size: 1rem;"><%= room.listing_name %></span> <% end %> <br/> <span class="badge bg-secondary text-light" style="position: relative; top: 0.01rem;">address</span><%= room.address %><br/><br/> <span class="badge bg-warning" style="font-size: 1rem;"><%= number_to_currency(room.price) %></span> </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>
ブラウザ確認
http://localhost:3000/
検索ページを作成します。
記述追加 GemFile
「gem 'ransack', '~> 2.3'」の記述追加(83行目)
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.6' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.0.3' # Use postgresql as the database for Active Record gem 'pg', '>= 0.18', '< 2.0' # Use Puma as the app server gem 'puma', '~> 4.1' # Use SCSS for stylesheets gem 'sass-rails', '>= 6' # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker gem 'webpacker', '~> 4.0' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.7' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 4.0' # Use Active Model has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Active Storage variant # gem 'image_processing', '~> 1.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.4.2', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '~> 3.2' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', '>= 2.15' gem 'selenium-webdriver' # Easy installation and use of web drivers to run system tests with browsers gem 'webdrivers' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] # Bulma gem 'bulma-rails', '~> 0.7.4' gem 'bulma-extensions-rails', '~> 1.0.30' # デバイス gem 'devise' # 日本語化 gem 'rails-i18n' # アマゾンS3 gem "aws-sdk" # アクションテキスト画像表示 gem "mini_magick" gem 'image_processing', '~> 1.2' #googleマップ gem 'geocoder', '~> 1.4' # facebook認証 gem 'omniauth', '= 1.9.0' gem 'omniauth-facebook', '= 5.0.0' # google認証 gem 'omniauth-google-oauth2' # 検索 gem 'ransack', '~> 2.3'
コマンド
bundle
記述追加 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 %>」に記述変更(7行目)
<div class="has-bg-img"> <h2 style="color: cornsilk; padding-top: 200px; padding-left: 50px;"> 札幌で民泊可能な部屋を掲載 <br> どんな部屋をお探しですか? </h2> <%= form_tag search_path, method: :get, data: { turbolinks: false} do %> <div class="row" style="padding: 50px;"> <div class="col-md-6"> <%= text_field_tag :search, params[:search], placeholder: "どんな部屋をお探しですか?", class: "form-control rounded-pill" %> </div> <div class="col-md-3"> <%= text_field_tag :start_date, params[:start_date], placeholder: "チェックイン", readonly: true, class: "form-control datepicker rounded-pill" %> </div> <div class="col-md-3"> <%= text_field_tag :end_date, params[:end_date], placeholder: "チェックアウト", readonly: true, class: "form-control datepicker rounded-pill" %> </div> </div> <div class="row" style="padding-left: 50px; padding-bottom: 50px;"> <div class="col-md-offset-4 col-md-4"> <%= submit_tag "検索 search", class: "btn btn-danger btn-block rounded-pill", style: "font-size: 1.3rem;" %> </div> </div> <% end %> </div> <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"> <%= link_to room_path(room), data: { turbolinks: false} do %> <%= image_tag room_cover(room), style: "width: 100%; height: 180;" %> <span class="badge bg-info text-light" style="font-size: 1rem;"><%= room.listing_name %></span> <% end %> <br/> <span class="badge bg-secondary text-light" style="position: relative; top: 0.01rem;">address</span><%= room.address %><br/><br/> <span class="badge bg-warning" style="font-size: 1rem;"><%= number_to_currency(room.price) %></span><br/>    </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>
Bootstrap5.0.2の機能「Collapse (コラプス)」を利用するため、「app/views/layouts/application.html.erb」ファイルに以下の記述を追加します。
記述追加 「app/views/layouts/application.html.erb」(19行目)
<!-- Bootstrap5.0.2使用のため --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
「app/views/layouts/application.html.erb」(19行目)
<!DOCTYPE html> <html> <head> <title>民泊予約サイト</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/vader/jquery-ui.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <!-- 日付ピッカーの日本語化--> <script src="https://rawgit.com/jquery/jquery-ui/master/ui/i18n/datepicker-ja.js"></script> <!-- Bootstrap5.0.2使用のため --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script> </head> <body> <!-- ナビゲーションバー --> <%= render "shared/navbar" %> <!-- noty --> <%= render 'shared/notification' %> <%= yield %> </body> </html>
スライーダーを使用できるように、iquery-uiの記述を追加します。
記述追加 app\javascript\packs\application.js
「require("jquery-ui/ui/widgets/slider");」の記述を13行目に追加
// This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. require("@rails/ujs").start() require("turbolinks").start() require("@rails/activestorage").start() require("channels") require('jquery'); require("jquery-ui/ui/widgets/datepicker"); require("jquery-ui/ui/widgets/slider"); require("raty-js") window.Noty = require("noty") window.Dropzone = require("dropzone") window.BulmaCarousel = require("bulma-extensions/bulma-carousel/dist/js/bulma-carousel") $(document).on('turbolinks:load', () => { $('.toggle').on('click', (e) => { e.stopPropagation(); e.preventDefault(); $('#' + e.target.getAttribute('aria-controls')).toggleClass('is-hidden'); }) }) // Uncomment to copy all static images under ../images to the output folder and reference // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>) // or the `imagePath` JavaScript helper below. // // const images = require.context('../images', true) // const imagePath = (name) => images(name, true) require("trix") require("@rails/actiontext")
「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"> <div class="col-md-offset-4 col-md-4"> <div id="filter" class="btn btn-danger btn-block rounded-pill" style="width: 40rem; margin-top: 1rem;" data-bs-toggle="collapse" data-bs-target="#collapsePanel" aria-expanded="false" aria-controls="collapsePanel"> 検索フィルター More filters<i class="fa fa-chevron-down"></i> </div> </div> </div> <br/> <br/> <div class="row"> <br/> <div class="collapse" 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> 宿泊費(円)</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 rounded-pill" %> </div> <div class="col-md-2"> <label>最高(円)</label> <%= f.text_field :price_lteq, class: "form-control rounded-pill" %> </div> </div> <hr/> <div class="row"> <div class="col-md-8"> <label><i class="far fa-calendar-alt"></i> 宿泊日</label> </div> <div class="col-md-6"> <%= text_field_tag :start_date, params[:start_date], readonly: true, placeholder: "チェックイン日", class: "form-control datepicker rounded-pill" %> </div> <div class="col-md-6"> <%= text_field_tag :end_date, params[:end_date], readonly: true, placeholder: "チェックアウト日", class: "form-control datepicker rounded-pill" %> </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> 宿泊人数</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> ベッド数</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> 部屋数</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> テレビ </div> <div class="col-md-4"> <%= check_box_tag "q[is_kitchen_eq]", true %> <i class="fas fa-blender"></i> キッチン </div> <div class="col-md-4"> <%= check_box_tag "q[is_Internet_eq]", true %> <i class="fas fa-wifi"></i> インターネット </div> <div class="col-md-4"> <%= check_box_tag "q[is_heating_eq]", true %> <i class="fab fa-hotjar"></i> 暖房 </div> <div class="col-md-4"> <%= check_box_tag "q[is_air_eq]", true %> <i class="fas fa-temperature-low"></i> エアコン </div> </div> <hr/> <div class="row text-center"> <%= f.submit "検索 search", class: "btn btn-danger btn-block", style: "font-size: 1.3rem;" %> </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_listing_name'>" + room.listing_name + "</div>"+"<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=AIzaSyDoAh6S8kEpArgzGFEvjT_0xK_VeUL5SEs&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" style="margin-left: 1rem; margin-bottom: 2rem;"> <%= link_to room_path(room), data: { turbolinks: false} do %> <%= image_tag room_cover(room), style: "width: 100%;" %> <h5 class="card-title"><span class="badge bg-dark text-light" style="font-size: 0.7rem;"><%= room.listing_name %></span></h5> <% end %> <span class="badge bg-success text-light"><%= room.home_type %></span> <span class="badge bg-info text-light"><%= room.accommodate %>名</span> <span class="badge bg-primary text-light">ベッド<%= room.bed_room %>台</span> <p class="subtitle is-6 m-b-5"><span class="badge bg-secondary text-light">Address</span><span style="position: relative; bottom: 0.8rem;"><%= room.address %></span></p> <div class="badge bg-warning" style="font-size: 1.1rem;"><%= number_to_currency(room.price) %></div> </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/
↓↓クリックして頂けると励みになります。
| 33 |レビューの実装 << [ホーム] >> | 35 |フルカレンダーの実装