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

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

【民泊5.1】【MacOSX】承認予約

コマンド
rails g migration AddInstantToRooms instant:bigint


記述追加 db\migrate\20200630034849_add_instant_to_rooms.rb
3行目に「, default: 1」の記述追加

class AddInstantToRooms < ActiveRecord::Migration[5.0]
  def change
    add_column :rooms, :instant, :bigint, default: 1
  end
end



コマンド
rails g migration AddStatusToReservations status:bigint


記述追加 db\migrate\20200630034925_add_status_to_reservations.rb
3行目に「, default: 0」の記述追加

class AddStatusToReservations < ActiveRecord::Migration[5.0]
  def change
    add_column :reservations, :status, :bigint, default: 0
  end
end



コマンド
rails db:migrate


記述追加 app\models\room.rb(3行目)

  #    instant: {承認制: 0, すぐに予約: 1}
  enum instant: {Request: 0, Instant: 1}



app\models\room.rb

class Room < ApplicationRecord

  #    instant: {承認制: 0, すぐに予約: 1}
  enum instant: {Request: 0, Instant: 1}

  belongs_to :user
  has_many :photos
  has_many :reservations
  has_many :guest_reviews

  geocoded_by :address
  after_validation :geocode, if: :address_changed?

  validates :home_type, presence: true
  validates :room_type, presence: true
  validates :accommodate, presence: true
  validates :bed_room, presence: true
  validates :bath_room, presence: true

  def cover_photo(size)
    if self.photos.length > 0
      self.photos[0].image.url(size)
    else
      "blank.jpg"
    end
  end

  def average_rating
    guest_reviews.count == 0 ? 0 : guest_reviews.average(:star).round(2).to_i
  end  

end



記述追加 app\models\reservation.rb(3行目)

  #    status: {承認待ち: 0, 承認: 1, 不承認: 2}
  enum status: {Waiting: 0, Approved: 1, Declined: 2}



app\models\reservation.rb

class Reservation < ApplicationRecord

  #    status: {承認待ち: 0, 承認: 1, 不承認: 2}
  enum status: {Waiting: 0, Approved: 1, Declined: 2}
  
  belongs_to :user
  belongs_to :room
end



記述追加 app\controllers\rooms_controller.rb
98行目に「, :instant」の記述追加

class RoomsController < ApplicationController
  before_action :set_room, except: [:index, :new, :create]
  before_action :authenticate_user!, except: [:show]
  before_action :is_authorised, only: [:listing, :pricing, :description, :photo_upload, :amenities, :location, :update]

  def index
     @rooms = current_user.rooms
  end

  def new
    @room = current_user.rooms.build
  end

  def create
    @room = current_user.rooms.build(room_params)
    if @room.save
      redirect_to listing_room_path(@room), notice: "保存しました。"
    else
      flash[:alert] = "問題が発生しました。"
      render :new
    end
  end

  def show
    @photos = @room.photos
    @guest_reviews = @room.guest_reviews
  end

  def listing
  end

  def pricing
  end

  def description
  end

  def photo_upload
      @photos = @room.photos
  end

  def amenities
  end

  def location
  end

  def update

    new_params = room_params
    new_params = room_params.merge(active: true) if is_ready_room

    if @room.update(new_params)
      flash[:notice] = "保存しました。"
    else
      flash[:alert] = "問題が発生しました。"
    end
    redirect_back(fallback_location: request.referer)
  end

  # 予約 開始日のAJAX
  def preload
    today = Date.today
    reservations = @room.reservations.where("start_date >= ? OR end_date >= ?", today, today)

    render json: reservations
  end

  # 予約 終了日のAJAX
  def preview
    start_date = Date.parse(params[:start_date])
    end_date = Date.parse(params[:end_date])

    output = {
      conflict: is_conflict(start_date, end_date, @room)
    }

    render json: output
  end

  private

    # 予約 プライベートメソッド
    def is_conflict(start_date, end_date, room)
      check = room.reservations.where("? < start_date AND end_date < ?", start_date, end_date)
      check.size > 0? true : false
    end

    def set_room
      @room = Room.find(params[:id])
    end

    def is_authorised
      redirect_to root_path, alert: "権限がありません。" unless current_user.id == @room.user_id
    end

    def is_ready_room
      !@room.active && !@room.price.blank? && !@room.listing_name.blank? && !@room.photos.blank? && !@room.address.blank?
    end

    def room_params
      params.require(:room).permit(:home_type, :room_type, :accommodate, :bed_room, :bath_room, :listing_name, :summary, :address, :is_tv, :is_kitchen, :is_air, :is_heating, :is_internet, :price, :active, :instant)
    end

end



記述追加 app\views\rooms\new.html.erb(48行目)

<div class="col-md-6 select">
  <div class="form-group">
    <label style="white-space: nowrap;">予約の種類(即時予約制:Instant, 承認予約制:Request)</label>
    <%= f.select :instant, Room.instants.map {|key,value| [key.humanize, key]}, selected: 'Instant', prompt: "選択してください", class: "form-control" %>
  </div>
</div>



app\views\rooms\new.html.erb

<div class="panel panel-default">
  <div class="panel-heading">
    お部屋の登録
  </div>
  <div class="panel-body">
    <div class="container">
      <%= form_for @room do |f| %>
        <div class="row">
          <div class="col-md-4 select">
            <div class="form-group">
              <label>お家のタイプ</label>
              <%= f.select :home_type, [["マンション", "マンション"], ["アパート", "アパート"], ["一戸建て", "一戸建て"]],
                             id: "home_type", prompt: "選択してください", class: "form-control" %>
            </div>
          </div>
          <div class="col-md-4 select">
            <div class="form-group">
              <label>お部屋のタイプ</label>
              <%= f.select :room_type, [ ["プライベート", "プライベート"], ["シェア", "シェア"]],
                            id: "room_type", prompt: "選択してください", class: "form-control" %>
            </div>
          </div>
          <div class="col-md-3 select">
            <div class="form-group">
              <label>宿泊可能人数</label>
              <%= f.select :accommodate, [["2人", 2], ["3人", 3], ["4人以上", 4]],
                            id: "accommodate", prompt: "選択してください", class: "form-control" %>
            </div>
          </div>
        </div>
        <div class="row">
 
          <div class="col-md-4 select">
            <div class="form-group">
              <label>ベッド数</label>
              <%= f.select :bed_room, [["1台", 1], ["2台", 2], ["3台", 3], ["4台以上", 4]],
                            id: "bed_room", prompt: "選択してください", class: "form-control" %>
            </div>
          </div>
          <div class="col-md-4 select">
            <div class="form-group">
              <label>部屋数</label>
              <%= f.select :bath_room, [["1部屋", 1], ["2部屋", 2], ["3部屋", 3], ["4部屋以上", 4]],
                            id: "bath_rooms", prompt: "選択してください", class: "form-control" %>
            </div>
          </div>

          <div class="col-md-6 select">
            <div class="form-group">
              <label style="white-space: nowrap;">予約の種類(即時予約制:Instant, 承認予約制:Request)</label>
              <%= f.select :instant, Room.instants.map {|key,value| [key.humanize, key]}, selected: 'Instant', prompt: "選択してください", class: "form-control" %>
            </div>
          </div>          

        </div>
        <br/>
        <br/>
        <br/>
        <div><%= f.submit "登録する", class: "btn btn-normal" %></div>
      <% end %>
    </div>
  </div>
</div>



ブラウザ確認
http://localhost:3000/rooms/new

予約の種類追加
予約の種類追加



記述追加 app\views\rooms\listing.html.erb(58行目)

<div class="col-md-8 select">
  <div class="form-group">
    <label style="white-space: nowrap;">予約の種類(即時予約制:Instant, 承認予約制:Request)</label>
      <%= f.select :instant, Room.instants.map {|key,value| [key.humanize, key]}, prompt: "選択してください", class: "form-control" %>
  </div>
</div>     



app\views\rooms\listing.html.erb

<div class="row">

  <div class="col-md-3">
    <%= render 'room_menu' %>
  </div>

  <div class="col-md-9">
    <div class="panel panel-default">
      <div class="panel-heading">
        お部屋の概要
      </div>
      <div class="panel-body">

        <div class="container">
            <%= form_for @room do |f| %>
                <div class="row">
                    <div class="col-md-4 select">
                        <div class="form-group">
                            <label>お家のタイプ</label>
                            <%= f.select :home_type, [["マンション", "マンション"], ["アパート", "アパート"], ["一戸建て", "一戸建て"]],
                                    id: "home_type", prompt: "選択してください", class: "form-control" %>
                        </div>
                    </div>
                    <div class="col-md-4 select">
                        <div class="form-group">
                        <label>お部屋のタイプ</label>
                        <%= f.select :room_type, [ ["プライベート", "プライベート"], ["シェア", "シェア"]],
                                        id: "room_type", prompt: "選択してください", class: "form-control" %>
                        </div>
                    </div>
                    <div class="col-md-3 select">
                        <div class="form-group">
                        <label>宿泊可能人数</label>
                        <%= f.select :accommodate, [["2人", 2], ["3人", 3], ["4人以上", 4]],
                                        id: "accommodate", prompt: "選択してください", class: "form-control" %>
                        </div>
                    </div>
                </div>

                <div class="row">
        
                  <div class="col-md-4 select">
                      <div class="form-group">
                      <label>ベッド数</label>
                      <%= f.select :bed_room, [["1台", 1], ["2台", 2], ["3台", 3], ["4台以上", 4]],
                                      id: "bed_room", prompt: "選択してください", class: "form-control" %>
                      </div>
                  </div>

                  <div class="col-md-4 select">
                      <div class="form-group">
                          <label>部屋数</label>
                          <%= f.select :bath_room, [["1部屋", 1], ["2部屋", 2], ["3部屋", 3], ["4部屋以上", 4]],
                                      id: "bath_rooms", prompt: "選択してください", class: "form-control" %>
                      </div>
                  </div>

                  <div class="col-md-8 select">
                    <div class="form-group">
                      <label style="white-space: nowrap;">予約の種類(即時予約制:Instant, 承認予約制:Request)</label>
                        <%= f.select :instant, Room.instants.map {|key,value| [key.humanize, key]}, prompt: "選択してください", class: "form-control" %>
                    </div>
                  </div>                    

                </div>
                <br/>
                <br/>
                <br/>
                <div><%= f.submit "修正する", class: "btn btn-normal" %></div>
            <% end %>
        </div>
      </div>
    </div>
  </div>
  
</div>



ブラウザ確認
http://localhost:3000/rooms/4/listing

部屋の編集に予約種類追加
部屋の編集に予約種類追加



記述追加 app\controllers\reservations_controller.rb(22行目)
「flash[:notice] = "予約が完了しました。"」の記述を以下に置き換えます。

        if @reservation.save
          if room.Request?
            flash[:notice] = "予約リクエストを送信しました。予約が承認されるまでしばらくお待ち下さい。"
          else
            @reservation.Approved!
            flash[:notice] = "予約が完了しました!ご予約ありがとうございます!"
          end
        else
          flash[:alert] = "ご予約できません!"
        end



app\controllers\reservations_controller.rb

class ReservationsController < ApplicationController
    
    before_action :authenticate_user!
  
    def create
      room = Room.find(params[:room_id])
  
      if current_user == room.user
        flash[:alert] = "オーナーが予約することはできません。"
      else
  
          start_date = Date.parse(reservation_params[:start_date])
          end_date = Date.parse(reservation_params[:end_date])
          days = (end_date - start_date).to_i + 1
  
          @reservation = current_user.reservations.build(reservation_params)
          @reservation.room = room
          @reservation.price = room.price
          @reservation.total = room.price * days
          @reservation.save
  
          if @reservation.save
            if room.Request?
              flash[:notice] = "予約リクエストを送信しました。予約が承認されるまでしばらくお待ち下さい。"
            else
              @reservation.Approved!
              flash[:notice] = "予約が完了しました!ご予約ありがとうございます!"
            end
          else
            flash[:alert] = "ご予約できません!"
          end
          
        end
        redirect_to room
    end

    def your_trips
      @trips = current_user.reservations.order(start_date: :asc)
    end    

    #ホスト用予約確認
    def your_reservations
      @rooms = current_user.rooms
    end

    private

    def reservation_params
        params.require(:reservation).permit(:start_date, :end_date)
    end
end
  
  



記述更新 app\views\reservations\_form.html.erb

3行目と40行目の記述を書き換えています。
コードをコピーしてファイルを置き換えて下さい。

<div class="panel panel-default">
  <div class="panel-heading">
    <!-- 承認制の場合はアイコンを表示しない -->
    <span><% if @room.Instant? %><i class="fa fa-bolt" style="color: #ffb400"></i><% end %></span>
    <span class="pull-right">1泊 <%= number_to_currency(@room.price) %></span>
    <br/>
  </div>
  <div class="panel-body">
    <%= form_for([@room, @room.reservations.new]) do |f| %>
      <div class="row">
        <div class="col-md-6">
          <label>チェックイン</label>
          <%= f.text_field :start_date, readonly: true, placeholder: "チェックイン日", class: "form-control datepicker" %>
        </div>
        <div class="col-md-6">
          <label>チェックアウト</label>
          <%= f.text_field :end_date, readonly: true, placeholder: "チェックアウト日", class: "form-control datepicker", disabled: true %>
        </div>
      </div>
      <h4 class="message-alert text-center"><span id="message"></span></h4>
      <div id="preview" style="display: none">
        <table class="reservation-table">
          <tbody>
             <tr>
               <td>宿泊費用</td>
               <td class="text-right", style="white-space: nowrap"><%= number_to_currency(@room.price) %></td>
             </tr>
             <tr>
               <td>宿泊日数</td>
               <td class="text-right"><span id="reservation_nights"></span></td>
             </tr>
             <tr>
               <td class="total">合計金額</td>
               <td class="text-right", style="white-space: nowrap"><span id="reservation_total"></span></td>
             </tr>
           </tbody>
        </table>
      </div>
      <br/>
      <% if @room.Instant? %>
        <%= f.submit "予約する", id: "btn_book", class: "btn btn-normal btn-block", disabled: true %>
      <% else %>
          <%= f.submit "予約承認申請を送る", id: "btn_book", class: "btn btn-normal btn-block", disabled: true %>
      <% end %>
    <% end %>
  </div>
</div>
<script>
  function checkDate(date) {
    dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
    return [$.inArray(dmy, unavailableDates) == -1];
  }
  $(function() {
    unavailableDates = [];
    $.ajax({
      url: '<%= preload_room_path(@room) %>',
      dateTyp: 'json',
      success: function(data) {
        $.each(data, function(arrID, arrValue) {
            for(var d = new Date(arrValue.start_date); d <= new Date(arrValue.end_date); d.setDate(d.getDate() + 1)) {
              unavailableDates.push($.datepicker.formatDate('d-m-yy', d));
            }
        });
        $('#reservation_start_date').datepicker({
          dateFormat: 'dd-mm-yy',
          //今日から3ヶ月先まで予約可能
          minDate: 0,
          maxDate: '3m',
          beforeShowDay: checkDate,
          onSelect: function(selected) {
            $('#reservation_end_date').datepicker("option", "minDate", selected);
            $('#reservation_end_date').attr("disabled", false);
            var start_date = $('#reservation_start_date').datepicker('getDate');
            var end_date = $('#reservation_end_date').datepicker('getDate');
            //2日選択すると1泊になる
            var nights = (end_date - start_date)/1000/60/60/24;
            var input = {
              'start_date': start_date,
              'end_date': end_date
            }
            $.ajax({
              url: '<%= preview_room_path(@room) %>',
              data: input,
              success: function(data) {
                if(data.conflict) {
                  $('#message').text("この日付はご利用できません。");
                  $('#preview').hide();
                  $('#btn_book').attr('disabled', true);
                } else {
                  $('#message').text("");
                  $('#preview').show();
                  $('#btn_book').attr('disabled', false);
                  var total = nights * <%= @room.price %>
                  $('#reservation_nights').text(nights);
                  $('#reservation_total').text(total);
                }
              }
            });
          }
        });
        $('#reservation_end_date').datepicker({
          dateFormat: 'dd-mm-yy',
          //今日から3ヶ月先まで予約可能
          minDate: 0,
          maxDate: '3m',
          beforeShowDay: checkDate,
          onSelect: function(selected) {
            $('#reservation_start_date').datepicker("option", "maxDate", selected);
            var start_date = $('#reservation_start_date').datepicker('getDate');
            var end_date = $('#reservation_end_date').datepicker('getDate');
            var nights = (end_date - start_date)/1000/60/60/24;
            var input = {
              'start_date': start_date,
              'end_date': end_date
            }
            $.ajax({
              url: '<%= preview_room_path(@room) %>',
              data: input,
              success: function(data) {
                if(data.conflict) {
                  $('#message').text("この日付ではご予約できません。");
                  $('#preview').hide();
                  $('#btn_book').attr('disabled', true);
                } else {
                  $('#message').text("");
                  $('#preview').show();
                  $('#btn_book').attr('disabled', false);
                  var total = nights * <%= @room.price %>
                  $('#reservation_nights').text(nights);
                  $('#reservation_total').text(total);
                }
              }
            });
          }
        });
      }
    });
  });
</script>



ブラウザ確認
http://localhost:3000/rooms/4


「app\controllers\reservations_controller.rb」ファイルを編集します。


1.記述追加 app\controllers\reservations_controller.rb(4行目)

before_action :set_reservation, only: [:approve, :decline]



2.記述追加 app\controllers\reservations_controller.rb(47行目)

    def approve
      @reservation.Approved!
      redirect_to your_reservations_path
    end
  
    def decline
      @reservation.Declined!
      redirect_to your_reservations_path
    end



3.記述追加 app\controllers\reservations_controller.rb(59行目)

    def set_reservation
      @reservation = Reservation.find(params[:id])
    end



記述追加 app\controllers\reservations_controller.rb

class ReservationsController < ApplicationController
    
    before_action :authenticate_user!
    before_action :set_reservation, only: [:approve, :decline]
  
    def create
      room = Room.find(params[:room_id])
  
      if current_user == room.user
        flash[:alert] = "オーナーが予約することはできません。"
      else
  
          start_date = Date.parse(reservation_params[:start_date])
          end_date = Date.parse(reservation_params[:end_date])
          days = (end_date - start_date).to_i + 1
  
          @reservation = current_user.reservations.build(reservation_params)
          @reservation.room = room
          @reservation.price = room.price
          @reservation.total = room.price * days
          @reservation.save
  
          if @reservation.save
            if room.Request?
              flash[:notice] = "予約リクエストを送信しました。予約が承認されるまでしばらくお待ち下さい。"
            else
              @reservation.Approved!
              flash[:notice] = "予約が完了しました!ご予約ありがとうございます!"
            end
          else
            flash[:alert] = "ご予約できません!"
          end

        end
        redirect_to room
    end

    def your_trips
      @trips = current_user.reservations.order(start_date: :asc)
    end    

    #ホスト用予約確認
    def your_reservations
      @rooms = current_user.rooms
    end

    def approve
      @reservation.Approved!
      redirect_to your_reservations_path
    end
  
    def decline
      @reservation.Declined!
      redirect_to your_reservations_path
    end

    private

    def set_reservation
      @reservation = Reservation.find(params[:id])
    end

    def reservation_params
        params.require(:reservation).permit(:start_date, :end_date)
    end
end
  
  



記述追加 config\routes.rb(37行目)

  resources :reservations, only: [:approve, :decline] do
    member do
      post '/approve' => "reservations#approve"
      post '/decline' => "reservations#decline"
    end
  end



config\routes.rb

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'

  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\reservations\your_reservations.html.erb」ファイルを編集します。


1.記述追加 app\views\reservations\your_reservations.html.erb(22行目)

<% if reservation.Waiting? %>
  <br/><p style="color: red;">承認待ちです。要確認</p>
<% elsif reservation.Approved? %>
  <br/><p style="color: green;">予約を承認しました</p>
<% else  %>
  <br/><p style="color: red;">予約を拒否しました</p>
<% end  %>

<div class="form-inline">
  <% if reservation.Waiting? %>
      <%= link_to approve_reservation_path(reservation), method: :post do %> <i class="fa fa-thumbs-up fa-lg"></i> <% end %> |
      <%= link_to decline_reservation_path(reservation), method: :post do %> <i class="fa fa-thumbs-down fa-lg"></i> <% end %>
  <% end %>
</div>



2.記述書換 app\views\reservations\your_reservations.html.erb(53行目)
54行目の記述を以下に書き換えます。

<%= render partial: "reviews/host_form", locals: {reservation: reservation}  if reservation.Approved? %>



app\views\reservations\your_reservations.html.erb

<div class="row">
  <div class="col-md-3">
    <ul class="sidebar-list">
      <li class="sidebar-item"><%= link_to "受注予約の一覧", your_reservations_path, class: "sidebar-link active" %></li>
      <li class="sidebar-item"><%= link_to "登録したお部屋の管理", rooms_path, class: "sidebar-link" %></li>
      <li class="sidebar-item"><%= link_to "お部屋の新規登録", new_room_path, class: "sidebar-link" %></li>
    </ul>
  </div>
  
  <div class="col-md-9">
    <div class="panel panel-default">
      <div class="panel-heading">
        受注予約の一覧
      </div>
      <div class="panel-body">
        <% @rooms.each do |room| %>
            <% room.reservations.each do |reservation| %>
                <div class="row">
                  <div class="col-md-3", style="white-space: nowrap">
                    <%= I18n.l(reservation.start_date, format: :full_date) %>

                    <% if reservation.Waiting? %>
                      <br/><p style="color: red;">承認待ちです。要確認</p>
                    <% elsif reservation.Approved? %>
                      <br/><p style="color: green;">予約を承認しました</p>
                    <% else  %>
                      <br/><p style="color: red;">予約を拒否しました</p>
                    <% end  %>
                    <div class="form-inline">
                      <% if reservation.Waiting? %>
                          <%= link_to approve_reservation_path(reservation), method: :post do %> <i class="fa fa-thumbs-up fa-lg"></i> <% end %> |
                          <%= link_to decline_reservation_path(reservation), method: :post do %> <i class="fa fa-thumbs-down fa-lg"></i> <% end %>
                      <% end %>
                    </div>                    

                  </div>

                  <div class="col-md-2">
                    <%= link_to room_path(reservation.room) do %>
                        <%= image_tag reservation.room.cover_photo(:thumb) %>
                    <% end %>
                  </div>
                  <div class="col-md-5">
                    <%= link_to reservation.room.listing_name, room_path(reservation.room) %><br/><br/>
                    <span>
                      <%= link_to user_path(reservation.user) do %>
                        <%= image_tag reservation.user.gravatar_url, class: "img-circle avatar-small" %>&nbsp;
                        <%= reservation.user.fullname %>
                      <% end %>
                    </span>
                  </div>
                  <div class="col-md-3 text-right">
                    <%= render partial: "reviews/host_form", locals: {reservation: reservation}  if reservation.Approved? %>
                  </div>
                </div>
                <hr/>
            <% end %>
        <% end %>
      </div>
    </div>
  </div>
</div>



「app\views\reservations\your_trips.html.erb」ファイルを編集します。


1.記述追加 app\views\reservations\your_trips.html.erb(18行目)

<% if trip.Waiting? %>
  <br/><p style="color: red;">承認待ちです。<br/>しばらくお待ち下さい。</p>
<% elsif trip.Approved? %>
  <br/><p style="color: green;">予約済みです</p>
<% else  %>
  <br/><p style="color: red;">予約できませんでした</p>
<% end  %>



2.記述書換 app\views\reservations\your_trips.html.erb(42行目)
43行目の記述を以下に書き換えます。

<%= render partial: "reviews/guest_form", locals: {reservation: trip} if trip.Approved? %>



app\views\reservations\your_trips.html.erb

<div class="row">
  <div class="col-md-3">
    <ul class="sidebar-list">
      <li class="sidebar-item"><%= link_to "ご予約の内容", your_trips_path, class: "sidebar-link active" %></li>
    </ul>
  </div>
  <div class="col-md-9">
    <div class="panel panel-default">
      <div class="panel-heading">
        ご予約内容
      </div>
      <div class="panel-body">
        <% @trips.each do |trip| %>
          <div class="row">
            <div class="col-md-3", style="white-space: nowrap">
              <%= I18n.l(trip.start_date, format: :full_date) %>

              <% if trip.Waiting? %>
                <br/><p style="color: red;">承認待ちです。<br/>しばらくお待ち下さい。</p>
              <% elsif trip.Approved? %>
                <br/><p style="color: green;">予約済みです</p>
              <% else  %>
                <br/><p style="color: red;">予約できませんでした</p>
              <% end  %>
              
            </div>
            <div class="col-md-2">
              <%= link_to room_path(trip.room) do %>
                <%= image_tag trip.room.cover_photo(:thumb) %>
              <% end %>
            </div>
            <div class="col-md-5">
              <%= link_to trip.room.listing_name, room_path(trip.room) %><br/><br/>
              <span>
                <%= image_tag trip.room.user.gravatar_url, class: "img-circle avatar-small" %>
                <%= link_to user_path(trip.room.user) do %>
                    <%= trip.room.user.fullname %>
                <% end %>
              </span>
            </div>
            <div class="col-md-3 text-right">
              <%= render partial: "reviews/guest_form", locals: {reservation: trip} if trip.Approved? %>
            </div>
          </div>
          <hr/>
        <% end %>
      </div>
    </div>
  </div>
</div>



「app\controllers\rooms_controller.rb」ファイルを編集します。


1.記述書換 app\controllers\rooms_controller.rb(63行目)
63行目を以下の記述に書き換えます。

reservations = @room.reservations.where("(start_date >= ? OR end_date >= ?) AND status = ?", today, today, 1)



2.記述書換 app\controllers\rooms_controller.rb(85行目)
85行目を以下の記述に書き換えます。

check = room.reservations.where("(? < start_date AND end_date < ?) AND status = ?", start_date, end_date, 1)



書き換え app\controllers\rooms_controller.rb

class RoomsController < ApplicationController

  before_action :set_room, except: [:index, :new, :create]
  before_action :authenticate_user!, except: [:show]
  before_action :is_authorised, only: [:listing, :pricing, :description, :photo_upload, :amenities, :location, :update]

  def index
     @rooms = current_user.rooms
  end

  def new
    @room = current_user.rooms.build
  end

  def create
    @room = current_user.rooms.build(room_params)
    if @room.save
      redirect_to listing_room_path(@room), notice: "保存しました。"
    else
      flash[:alert] = "問題が発生しました。"
      render :new
    end
  end

  def show
    @photos = @room.photos
    @guest_reviews = @room.guest_reviews
  end

  def listing
  end

  def pricing
  end

  def description
  end

  def photo_upload
      @photos = @room.photos
  end

  def amenities
  end

  def location
  end

  def update
    new_params = room_params
    new_params = room_params.merge(active: true) if is_ready_room
    if @room.update(new_params)
      flash[:notice] = "保存しました。"
    else
      flash[:alert] = "問題が発生しました。"
    end
    redirect_back(fallback_location: request.referer)
  end

  # 予約 開始日のAJAX
  def preload
    today = Date.today
    reservations = @room.reservations.where("(start_date >= ? OR end_date >= ?) AND status = ?", today, today, 1)
    render json: reservations
  end

  # 予約 終了日のAJAX
  def preview
    start_date = Date.parse(params[:start_date])
    end_date = Date.parse(params[:end_date])
    output = {
      conflict: is_conflict(start_date, end_date, @room)
    }
    render json: output
  end

  private

  # 予約 プライベートメソッド
  def is_conflict(start_date, end_date, room)
    check = room.reservations.where("(? < start_date AND end_date < ?) AND status = ?", start_date, end_date, 1)
    check.size > 0? true : false
  end

  def set_room
      @room = Room.find(params[:id])
  end
  
  def is_authorised
    redirect_to root_path, alert: "権限がありません。" unless current_user.id == @room.user_id
  end

  def is_ready_room
    !@room.active && !@room.price.blank? && !@room.listing_name.blank? && !@room.photos.blank? && !@room.address.blank?
  end

  def room_params
    params.require(:room).permit(:home_type, :room_type, :accommodate, :bed_room, :bath_room, :listing_name, :summary, :address, :is_tv, :is_kitchen, :is_air, :is_heating, :is_internet, :price, :active, :instant)
  end

end



書き換え app\controllers\pages_controller.rb(37行目から)

        not_available = room.reservations.where(
          "((? <= start_date AND start_date <= ?)
          OR (? <= end_date AND end_date <= ?)
          OR (start_date < ? AND ? < end_date))
          AND status = ?",
          start_date, end_date,
          start_date, end_date,
          start_date, end_date,
          1
        ).limit(1)



app\controllers\pages_controller.rb

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))
          AND status = ?",
          start_date, end_date,
          start_date, end_date,
          start_date, end_date,
          1
        ).limit(1)

        if not_available.length > 0
          @arrRooms.delete(room)
        end
      end
    end
  end
  
end



ブラウザ確認
承認制のお部屋を予約すると承認待ちの状態になります。
http://localhost:3000/your_trips


ステータス:承認待ち
ステータス:承認待ち


ホスト側で承認するかしないかを決めることができます。
http://localhost:3000/your_reservations


ホストは承認するかどうか決める
ホストは承認するかどうか決める


承認するとレビューボタンがでます。
承認:レビューボタン
承認:レビューボタン


承認されるとゲスト側でもレビューボタンがでます。
承認:レビューボタン
承認:レビューボタン

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

関連記事(外部サイト)