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

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

【民泊5.1】【Windows】フルカレンダー

記述追加 GemFile(85行目)

gem 'fullcalendar-rails', '~> 3.4.0'
gem 'momentjs-rails', '~> 2.17.1'



GemFile

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.7', '>= 5.0.7.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# 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.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

#bootstrap
gem 'bootstrap-sass', '~> 3.4.1'

#デバイス
gem 'devise', '~>4.2'

#Gravatar
gem 'gravtastic'

#フラッシュメッセージ
gem 'toastr-rails', '~> 1.0'

#日本語化
gem 'rails-i18n'

#画像アップロード
gem 'paperclip', '~> 5.1.0'

#googleマップ
gem 'geocoder', '~> 1.4'

#アマゾンS3
gem 'aws-sdk', '~> 2.8'

#日付ピッカー
gem 'jquery-ui-rails', '~> 5.0'

# 検索
gem 'ransack', '~> 1.7'

# 電話番号認証
gem 'twilio-ruby', '~> 4.11.1'

# フルカレンダー
gem 'fullcalendar-rails', '~> 3.4.0'
gem 'momentjs-rails', '~> 2.17.1'



記述追加 app\assets\javascripts\application.js(19行目)

//= require moment
//= require fullcalendar



app\assets\javascripts\application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require jquery-ui/datepicker
//= require jquery-ui/slider
//= require toastr
//= require moment
//= require fullcalendar
//= require gravtastic
//= require turbolinks
//= require_tree .



記述追加 app\assets\stylesheets\application.scss
24行目に「@import "fullcalendar";」の記述追加

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

 //bootstrap
 @import "bootstrap-sprockets";
 @import "bootstrap"; 

 //フラッシュメッセージ
 @import "toastr";

 //フルカレンダー
 @import "fullcalendar";


 //基本の設定
 body {
    color: #565a5c;
    background-color: #F8F8F8;
    font-family: "Kosugi", sans-serif;
  }
  
  a {
    color: #00A699;
  }
  
  .container {
    width: 80%;
  }
  
  .text-babu, .icon-babu {
    color: #00A699;
  }
  
  .text-red, .icon-red {
    color: #FF5A5F;
  }
  
  // ナビゲーションバー
  .navbar-default {
    background-color: #FFFFFF;
  }
  
  .navbar-default .navbar-brand {
    color: #FF5A5F;
    font-size: 2em;
    font-weight: 400;
  }
  
  // ボタン
  .btn-block {
    display: block;
    white-space: normal;
    width: 100%;
  }
  
  .btn {
    color: #fff;
    border-radius: 5px;
    font-weight: bold;
    padding: 9px 27px;
  }
  
  .btn-small {
    padding: 5px 15px;
    margin-top: 15px;
  }
  
  .btn:hover, .btn:focus {
    color: #fff;
  }
  
  .btn.btn-default {
    width: 100%;
    border-color: #c4c4c4;
    background: white;
    color: #484848;
    border-radius: 2px;
    padding: 10px 0;
    margin-top: 10px;
  }
  
  .btn.btn-normal {
    border: 1px solid #ff5a5f;
    background-color: #ff5a5f;
  }
  
  .btn.btn-normal:active {
    outline: none;
    border-color: #e00007;
    background-color: #e00007;
  }
  
  .btn.btn-form {
    border: 1px solid #00A699;
    background-color: #00A699;
  }
  
  .btn.btn-form:active {
    outline: none;
    border-color: #066165;
    background-color: #066165;
  }
  
  .btn.btn-facebook {
    border: 1px solid #3B5998;
    background-color: #3B5998;
  }
  
  .btn.btn-facebook:active {
    outline: none;
    border-color: #2d467b;
    background-color: #2d467b;
  }
  
  // パネル
  .panel-default .panel-heading {
    color: #ffffff;
    background-color: #00A699;
    font-size: 18px;
    font-weight: 400;
  }
  
  .row-space-1 {
    margin-top: 6px;
    margin-bottom: 6px;
  }
  
  .row-space-2 {
    margin-top: 12px;
    margin-bottom: 12px;
  }
  
  .row-space-3 {
    margin-top: 24px;
    margin-bottom: 24px;
  }
  
  .description {
    color: #575757;
    font-size: 15px;
    font-weight: 500;
    line-height: 25px;
  }
  
  // アバター
  .avatar-small {
    width: 28px;
  }
  
  .avatar-medium {
    width: 48px;
  }
  
  .avatar-large {
    width: 68px;
  }
  
  .avatar-full {
    width: 100%;
  }
  
  // フォーム
  .form-group {
    margin-bottom: 25px;
  }
  
  .form-control {
    border-radius: 2px;
    height: 4rem;
  }
  
  .form-group input {
    height: 45px;
    border: 1px solid #00A699;
  }
  
  .form-group textarea {
    border: 1px solid #00A699;
  }
  
  .form-group input[type="radio"] {
    height: 15px;
    margin-right: 10px;
  }
  
  .btn-group label {
    margin-right: 15px;
  }
  
  .form-group select {
    width: 100%;
    color: #565a5c;
    background-color: white;
    border: 1px solid #00A699;
    border-radius: 2px;
    padding: 10px;
    appearance: none;
    -moz-appearance: none; /* Firefox */
    -webkit-appearance: none; /* Safari & Chrome */
  }
  
  .select:before {
    content: '\25bc';
    font-size: 1.2em;
    position: absolute;
    color: #00A699;
    top: 35px;
    right: 30px;
    transform: scale(0.94, 0.62);
  }
  
  .form-group input[type="checkbox"] {
    height: 1.25em;
    width: 1.25em;
    margin-bottom: -0.25em;
    margin-right: 5px;
    vertical-align: top;
    border: 1px solid #00A699;
    border-radius: 2px;
    appearance: none;
    -moz-appearance: none;
    -webkit-appearance: none;
  }
  
  .form-group input[type="checkbox"]:checked:before {
    content: '\2713';
    position: absolute;
    font-size: 0.95em;
    text-align: center;
    width: 1.25em;
    color: #00A699;
  }
  
  // スライダー
  .sidebar-list {
    padding-left: 0;
    list-style: none;
  }
  
  .sidebar-item {
    padding: 10px 0;
    font-size: 16px;
    color: #82888a;
  }
  
  .sidebar-link {
    color: #82888a;
    text-decoration: none;
  }
  
  .sidebar-link:hover, .sidebar-link:focus {
    color: #CACCCD;
    text-decoration: none;
  }
  
  .active.sidebar-link {
    color: #565A5C;
    font-weight: bold;
    text-decoration: none;
  }
  
  // 画像アップロード
  .btn-file {
    position: relative;
    overflow: hidden;
  }
  
  .btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
  }
  
  .panel-heading.preview {
    padding: 0;
  }
  
  .panel-heading.preview img {
    width: 100%;
  }
  
  // 部屋の表示
  .amenities li {
    margin-bottom: 10px;
    font-size: 16px;
    list-style-type: none;
  }
  
  .amenities .text-line-through {
    text-decoration: line-through;
    color: rgba(0,0,0,0.45);
    font-size: 14px;
  }
  
  // 予約
  .reservation-table td {
    width: 100%;
    border: none;
    border-bottom: 1px solid #dce0e0;
    padding: 10px;
  }
  
  .reservation-table .total td {
    font-size: 16px;
    font-weight: bold;
    border: none;
  }
  
  .form-control.datepicker {
    color: #00A699;
    background-color: white;
    border: 1px solid #00A699;
    text-align: center;
  }
  
  .message-alert {
    color: #d43242;
    font-size: 14px;
    padding-top: 10px;
  }
  
  // 検索
  #main {
    height: 100%;
    overflow: hidden;
  }
  
  #left {
    padding: 10px 400px 10px 20px;
    overflow: scroll;
    height: 100%;
  }
  
  #right {
    position: fixed;
    top: 0;
    right: 0;
    width: 450px;
    height: 100%;
  }
  
  .map_price {
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    color: #00A699;
  }
  
  // ホームページ
  .discovery-card {
    background-size: cover;
    background-position: center;
    height: 326px;
  }
  
  .banner {
    margin-top: 50px;
    margin-bottom: 50px;
  }
  
  // カレンダー
  .fc-content.Waiting {
    background-color: #C9CC6D;
  }
  
  .fc-past {
    background-color: lightgray;
  }
  
  .fc-day {
    position: relative;
  }
  
  .fc-content {
    background-color: #00A699;
    height: 40px;
    border-radius: 20px;
  }
  
  .fc-event {
    border: 0px;
    background-color: transparent;
  }
  
  .fc-title {
    font-size: 14px;
    position: relative;
    top: 7px;
    left: 20px;
  }
  
  .day-price {
    position: absolute;
    color: #EAA90B;
    bottom: 2px;
    right: 2px;
  }
  
  .badge {
    background-color: #FF5A5F;
    position: relative;
    top: -15px;
    left: -5px;
  }
  
  #add-card form {
    width: 480px;
    margin: 20px auto;
  }
  
  #add-card label {
    position: relative;
    color: #6A7C94;
    font-weight: 400;
    height: 48px;
    line-height: 48px;
    margin-bottom: 10px;
    display: block;
  }
  
  #add-card label > span {
    float: left;
  }
  
  .field {
    background: white;
    box-sizing: border-box;
    font-weight: 400;
    border: 1px solid #CFD7DF;
    border-radius: 24px;
    color: #32315E;
    outline: none;
    height: 48px;
    line-height: 48px;
    padding: 0 20px;
    cursor: text;
    width: 76%;
    float: right;
  }
  
  .field::-webkit-input-placeholder { color: #CFD7DF; }
  .field::-moz-placeholder { color: #CFD7DF; }
  .field:-ms-input-placeholder { color: #CFD7DF; }
  
  .field:focus,
  .field.StripeElement--focus {
    border-color: #F99A52;
  }
  
  #add-card button {
    float: left;
    display: block;
    background-image: linear-gradient(-180deg, #F8B563 0%, #F99A52 100%);
    box-shadow: 0 1px 2px 0 rgba(0,0,0,0.10), inset 0 -1px 0 0 #E57C45;
    color: white;
    border-radius: 24px;
    border: 0;
    margin-top: 20px;
    font-size: 17px;
    font-weight: 500;
    width: 100%;
    height: 48px;
    line-height: 48px;
    outline: none;
  }
  
  #add-card button:focus {
    background: #EF8C41;
  }
  
  #add-card button:active {
    background: #E17422;
  }
  
  .outcome {
    float: left;
    width: 100%;
    padding-top: 8px;
    min-height: 20px;
    text-align: center;
  }
  
  .success, .error {
    display: none;
    font-size: 13px;
  }
  
  .success.visible, .error.visible {
    display: inline;
  }
  
  .error {
    color: #E4584C;
  }
  



コマンド
bundle


ユーザテーブルにアバター画像用のカラムを追加します。


コマンド
rails g migration AddFieldsToUser provider:string uid:string image:string


コマンド
rails db:migrate


Gravatar画像用のヘルパーを用意します。


app\helpers\application_helper.rb

module ApplicationHelper
    def avatar_url(user)
        gravatar_id = Digest::MD5::hexdigest(user.email).downcase
        "https://www.gravatar.com/avatar/#{gravatar_id}.jpg?d=identical&s=150"
    end    
end



「app\controllers」フォルダに「calendars_controller.rb」ファイルを新規作成します。


app\controllers\calendars_controller.rb(新規作成したファイル)

class CalendarsController < ApplicationController
  before_action :authenticate_user!
  include ApplicationHelper

  def host
    @rooms = current_user.rooms

    params[:start_date] ||= Date.current.to_s
    params[:room_id] ||= @rooms[0] ? @rooms[0].id : nil

    if params[:q].present?
      params[:start_date] = params[:q][:start_date]
      params[:room_id] = params[:q][:room_id]
    end

    @search = Reservation.ransack(params[:q])


    if params[:room_id]
      @room = Room.find(params[:room_id])
      start_date = Date.parse(params[:start_date])

      first_of_month = (start_date - 1.months).beginning_of_month # 最初の月の1日から
      end_of_month = (start_date + 1.months).end_of_month # => 3ヶ月後の31まで

      @events = @room.reservations.joins(:user)
                      .select('reservations.*, users.fullname, users.image, users.email, users.uid')
                      .where('(start_date BETWEEN ? AND ?) AND status <> ?', first_of_month, end_of_month, 2)
      @events.each{ |e| e.image = avatar_url(e) }

    else
      @room = nil
      @events = []

    end
  end

end

  
  



記述追加 config\routes.rb
11行目に「get '/host_calendar' => "calendars#host"」の記述追加

Rails.application.routes.draw do

  #ルートをpages#homeに設定
  root 'pages#home'

  get 'pages/home'
  get '/your_trips' => 'reservations#your_trips'
  get '/your_reservations' => 'reservations#your_reservations'
  get 'search' => 'pages#search'
  get 'dashboard' => 'dashboards#index'
  get '/host_calendar' => "calendars#host"

  resources :users, only: [:show] do
    member do
      post '/verify_phone_number' => 'users#verify_phone_number'
      patch '/update_phone_number' => 'users#update_phone_number'
    end
  end

  resources :rooms, except: [:edit] do
    member do
      get 'listing'
      get 'pricing'
      get 'description'
      get 'photo_upload'
      get 'amenities'
      get 'location'
      get 'preload'
      get 'preview'
    end
    resources :photos, only: [:create, :destroy]
    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

  devise_for :users,
  path: '',
  path_names: {sign_in: 'login', sign_out: 'logout', edit: 'profile', sign_up: 'registration'},
  controllers: {registrations: 'registrations'}
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end



「app\views」フォルダに「calendars」フォルダを新規作成します。
作成した「calendars」フォルダに「host.html.erb」ファイルを新規作成します。



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

<% if !@rooms.blank? %>
  <div class="row">
    <%= search_form_for @search, class: 'form-group', remote: true, url: host_calendar_path do |f| %>
      <div class="col-md-6 select">
        <div class="form-group">
          <label>登録しているお部屋</label>
          <%= f.select :room_id, options_for_select(@rooms.collect {|u| [u.listing_name, u.id]}, params[:room_id]), {}, {
            onchange: "this.form.submit();",
            class: "form-control"
          } %>
        </div>
      </div>

      <%= f.hidden_field :start_date, id: "start-date", value: params[:start_date], onchange: "$(this.form).submit()" %>
    <% end %>
  </div>
<% end %>


<div id="calendar"></div>

<script>
  window.reservations = <%= raw @events.to_json %>
  console.log(reservations);

  function showReservations(data) {
    return data.map(function (e) {

      if (e['start_date'] !== e['end_date']) {
         e['end_date'] = moment.utc(e['end_date']).add(1, 'days')
       }

      return {
        name: e.fullname,
        start: e['start_date'],
        end: e['end_date'],
        avatar: e.image,
        status: e.status
      }
    })
  }


  $('#calendar').fullCalendar({
    header: {
      left: 'title',
      center: '',
      right: 'prev,next'
    },
    defaultDate: $('#start-date').val(),
    events: showReservations(reservations),
    eventRender: function(event, element, view) {
      return $(`
        <a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end">
          <div class="fc-content ${event.status}">
            <span class="fc-title"><img class="img-circle avatar-small" src="${event.avatar}"> ${event.name}</span>
          </div>
        </a>
      `);
    }
  });


  $('.fc-prev-button').click(function() {
  var current = new Date($('#start-date').val());
  var prev = new Date(current.getFullYear(), current.getMonth() - 1, 1)
  $('#start-date').val(moment(prev).format('YYYY-MM-DD'))
  $('#start-date').trigger('change')
});

$('.fc-next-button').click(function() {
  var current = new Date($('#start-date').val());
  var next = new Date(current.getFullYear(), current.getMonth() + 1, 1)
  $('#start-date').val(moment(next).format('YYYY-MM-DD'))
  $('#start-date').trigger('change')
});


</script>



「app\views\calendars」フォルダに「host.js.erb」ファイルを新規作成します。


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

reservations = <%= raw @events.to_json %>

$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', showReservations(reservations));
$('#calendar').fullCalendar('rerenderEvents');



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


予約のカレンダー表示
予約のカレンダー表示

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

関連記事(外部サイト)