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

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

Ruby on Rails6.0 | 空き部屋を登録・予約・決済できるWebサイトを作成する 40 | 承認予約

[39]ステータス表示<< [ホームに戻る] >> [41]クレジットカード決済 | Stripe(ストライプ)


コマンド
rails g migration AddInstantToRooms instant:bigint


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

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



コマンド
rails g migration AddStatusToReservations status:bigint


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

class AddStatusToReservations < ActiveRecord::Migration[6.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 :reservations
  has_many :guest_reviews
  has_many :reviews

  has_many_attached :photos
  has_rich_text :description

  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 average_rating
    guest_reviews.count == 0 ? 0 : guest_reviews.average(:stars).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

  has_many :reviews
end



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


1.75行目を以下の記述に書き換えます。

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



2.108行目を以下の記述に書き換えます。

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



3.95行目に「, :instant」の記述追加

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, :description, :instant)



記述追加 app\controllers\rooms_controller.rb

class RoomsController < ApplicationController

  protect_from_forgery except: [:upload_photo]
  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
  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

  def upload_photo
    @room.photos.attach(params[:file])
    render json: { success: true }
  end

  def delete_photo
    @image = ActiveStorage::Attachment.find(params[:photo_id])
    @image.purge
    redirect_to photo_upload_room_path(@room)
  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 set_room
      @room = Room.find(params[:id])
    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, :description, :instant)
    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 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

  end



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


1.3行目に以下の記述を追加します。

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



2.22行目の記述「flash[:notice] = "予約が完了しました。"」を以下の記述に書き換えます。

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



3.45行目から「approve()」と「decline()」メソッド追加。

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



4.60行目にプライベートメソッド「set_reservation()」を追加しています。

    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 reservation_params
    params.require(:reservation).permit(:start_date, :end_date)
  end

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



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

        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



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

  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

  # ルートを 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]

  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\rooms\new.html.erb(58行目から68行目)

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



app\views\rooms\new.html.erb

<section class="section">
    <div class="container">
        <article class="panel">
            <div class="panel-heading">
                お部屋の登録
            </div>
            <div class="card">
                <div class="card-content">
                    <div class="media">
                        <%= form_for @room do |f| %>
                            <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>
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            <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>
                            <br/>
                            <br/>
                            <br/>
                            <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>
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            <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>
                            <br/>
                            <br/>
                            <br/>
                            <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>
                            <br/>
                            <br/>
                            <br/>

                            <div class="col-md-6 select">
                                <div class="form-group">
                                    <label>予約種別</label>
                                    <%= f.select :instant, Room.instants.map {|key,value| [key.humanize, key]}, selected: 'Instant', prompt: "選択してください", class: "form-control" %>
                                </div>
                                <label>即時予約制:Instant, 承認予約制:Request</label>
                            </div>
                            <br/>
                            <br/>
                            <br/>
                            <br/>
                                                        
                            <br/>
                            <div><%= f.submit "登録する", class: "button is-primary" %></div>
                        <% end %>
                    </div>
                </div>
            </div>
        </article>
    </div>
</section>



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

予約種別追加
予約種別追加



記述追加 app\views\rooms\listing.html.erb(72行目から82行目)

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



app\views\rooms\listing.html.erb

<section class="section">
    <div class="container">
        <div class="columns">
        
            <!-- 左パネル -->
            <div class="column is-one-third">
                <div class="columns is-multiline">
                    <div class="col-md-3">
                        <%= render 'room_menu' %>
                    </div>
                <br/>
                </div>
            </div>
            <!-- 右側 -->
            <div class="column">
                <div class="columns is-multiline">
                    <article class="panel">
                        <div class="panel-heading">
                             お部屋の概要
                        </div>
                        <div class="card">
                            <div class="card-content">
                                <div class="media">
                                    <%= form_for @room do |f| %>
                                        <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>
                                        &nbsp;&nbsp;&nbsp;&nbsp;
                                        <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>
                                        <br/>
                                        <br/>
                                        <br/>
                                        <div class="col-md-4 select">
                                            <div class="form-group">
                                                <label>宿泊可能人数</label>
                                                <%= f.select :accommodate, [["2人", 2], ["3人", 3], ["4人以上可能", 4]],
                                                    id: "accommodate", prompt: "選択してください", class: "form-control" %>
                                            </div>
                                        </div>
                                        &nbsp;&nbsp;&nbsp;&nbsp;
                                        <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>
                                        <br/>
                                        <br/>
                                        <br/>
                                        <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>
                                        <br/>
                                        <br/>
                                        <br/>

                                        <div class="col-md-6 select">
                                            <div class="form-group">
                                                <label>予約種別</label>
                                                <%= f.select :instant, Room.instants.map {|key,value| [key.humanize, key]}, selected: 'Instant', prompt: "選択してください", class: "form-control" %>
                                            </div>
                                            <label>即時予約制:Instant, 承認予約制:Request</label>
                                        </div>
                                        <br/>
                                        <br/>
                                        <br/>
                                        <br/>
                                                                        
                                        <br/>
                                        <div><%= f.submit "修正する", class: "button is-primary" %></div>
                                    <% end %>
                                </div>
                            </div>
                        </div>
                    </article>
                </div>
            </div>
        </div>
    </div>
</section>



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

予約種別追加
予約種別追加



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


1.4行目を以下の記述に変更します。

    <!-- 承認制の場合はアイコンを表示しない -->
    <span><% if @room.Instant? %><i class="fas fa-chess-king" style="color: #ffb400"></i><% end %></span>&nbsp;&nbsp;&nbsp;



2.56行目の記述を以下の記述に変更します。

<% if @room.Instant? %>
  <%= f.submit "予約する", id: "btn_book", class: "button is-danger is-fullwidth m-t-10 m-b-10", disabled: true %>
<% else %>
    <%= f.submit "予約承認申請を送る", id: "btn_book", class: "button is-danger is-fullwidth m-t-10 m-b-10", disabled: true %>
<% end %>



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

<div class="card">
  <header class="card-header">
    <p class="card-header-title">
    <!-- 承認制の場合はアイコンを表示しない -->
    <span><% if @room.Instant? %><i class="fas fa-chess-king" style="color: #ffb400"></i><% end %></span>&nbsp;&nbsp;&nbsp;
    <span class="pull-right">1泊 <%= number_to_currency(@room.price) %></span>
    </p>
  </header>
  <div class="card-content">
    <div class="content">

      <%= form_for([@room, @room.reservations.new]) do |f| %>

        <div class="field is-horizontal">
            <div class="field-body">
                <div class="field">
                <p class="control is-expanded has-icons-left">
                    <%= f.text_field :start_date, readonly: true, placeholder: "イン", class: "input is-primary is-rounded" %>
                    <span class="icon is-small is-left">
                    <i class="far fa-calendar-alt"></i>
                    </span>
                </p>
                </div>
                <div class="field">
                <p class="control is-expanded has-icons-left has-icons-right">
                    <%= f.text_field :end_date, readonly: true, placeholder: "アウト", class: "input is-primary is-rounded" %>
                    <span class="icon is-small is-left">
                    <i class="far fa-calendar-alt"></i>
                    </span>

                </p>
                </div>
            </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>

        <% if @room.Instant? %>
          <%= f.submit "予約する", id: "btn_book", class: "button is-danger is-fullwidth m-t-10 m-b-10", disabled: true %>
        <% else %>
            <%= f.submit "予約承認申請を送る", id: "btn_book", class: "button is-danger is-fullwidth m-t-10 m-b-10", disabled: true %>
        <% end %>

      <% end %>
    </div>
  </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\views\reservations\your_reservations.html.erb」ファイルを編集していきます。


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

<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>
<% if reservation.Waiting? %>
<p class="tag is-warning">承認待ちです。要確認</p>
<% elsif reservation.Approved? %>
<p class="tag is-success">予約を承認しました</p>
<% else  %>
<p class="tag is-danger">予約を拒否しました</p>
<% end  %>



2.71行目に「 if reservation.Approved?」の記述を追加します。

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



app\views\reservations\your_reservations.html.erb

<section class="section">
    <div class="container">
        <p class="title">受注予約の一覧</p>
        <br/>

        <table class="table is-fullwidth" style="text-align: center;">
            <thead>
                <tr>
                    <th>申し込み日</th>
                    <th>ステータス</th>
                    <th>お部屋</th>
                    <th>ゲスト</th>
                    <th></th>
                    <th>料金</th>
                    <th>アクション</th>
                </tr>
            </thead>
            <tbody>
                <% if @rooms.blank? %>
                  <tr>
                      <td colspan="7" class="has-text-centered"><h1>表示できる受注予約はありません。</h1></td>
                  </tr>
                <% end %>
        <% @rooms.each do |room| %>
            <% room.reservations.each do |reservation| %>
                    <tr>
                        <td style="padding-top: 30px;"><%= I18n.l(reservation.created_at, format: :full_date) %></td>

                        <!-- ステータス -->
                        <td style="padding-top: 30px;">
                            <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>
                            <% if reservation.Waiting? %>
                            <p class="tag is-warning">承認待ちです。要確認</p>
                            <% elsif reservation.Approved? %>
                            <p class="tag is-success">予約を承認しました</p>
                            <% else  %>
                            <p class="tag is-danger">予約を拒否しました</p>
                            <% end  %>
                        </td>

                        <td>
                            <%= link_to room_path(reservation.room), data: { turbolinks: false} do %>                                
                                <%= image_tag room_cover(reservation.room), class: "image is-64x64" %>
                                <%= reservation.room.listing_name %>
                            <% end %>
                        </td>

                        <td style="padding-top: 30px;">
                            <%= link_to user_path(reservation.user), class: "tootip" do %>
                                <figure class="image is-48x48">
                                    <%= image_tag avatar_url(reservation.user), class: "is-rounded" %>
                                </figure>
                                <%= reservation.user.full_name %>
                            <% end %>
                        </td>

                        <td style="padding-top: 30px;">
                            宿泊日:<%= I18n.l(reservation.start_date, format: :full_date) %><br/>
                            ご出発:<%= I18n.l(reservation.end_date, format: :full_date) %>
                        </td>

                        <td style="padding-top: 30px;"><%= number_to_currency(reservation.total) %></td>

                        <!-- アクション -->
                        <td style="padding-top: 30px;">
                            <%= render partial: "reviews/host_form", locals: {reservation: reservation}  if reservation.Approved? %>
                        </td>

                    </tr>
                <% end %>
                <% end %>
            </tbody>
        </table>


    </div>
</section>



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


承認予約時に「アップボタン」と「ダウンボタン」が表示されます。

承認予約時の表示
承認予約時の表示



アップボタンを押すと予約が承認され、レビューボタンが表示されます。

予約承認
予約承認



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


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

<% if trip.Waiting? %>
    <p class="tag is-warning">承認待ちです。しばらくお待ち下さい。</p>
<% elsif trip.Approved? %>
    <p class="tag is-success">予約済みです</p>
<% else  %>
    <p class="tag is-warning">予約できませんでした</p>
<% end  %>



2.66行目に「 if trip.Approved?」の記述を追加します。

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



app\views\reservations\your_trips.html.erb

<section class="section">
    <div class="container">
        <p class="title">ご予約内容</p>
        <br/>

        <table class="table is-fullwidth" style="text-align: center;">
            <thead>
                <tr>
                    <th>申し込み日</th>
                    <th>ステータス</th>
                    <th>お部屋</th>
                    <th>ホスト</th>
                    <th></th>
                    <th>料金</th>
                    <th>アクション</th>
                </tr>
            </thead>
            <tbody>
                <% if @trips.blank? %>
                  <tr>
                      <td colspan="7" class="has-text-centered"><h1>表示できるご予約はありません。</h1></td>
                  </tr>
                <% end %>
                <% @trips.each do |trip| %>
                    <tr>
                        <td style="padding-top: 30px;"><%= I18n.l(trip.created_at, format: :full_date) %></td>

                        <!-- ステータス -->
                        <td style="padding-top: 30px;">

                            <% if trip.Waiting? %>
                                <p class="tag is-warning">承認待ちです。しばらくお待ち下さい。</p>
                            <% elsif trip.Approved? %>
                                <p class="tag is-success">予約済みです</p>
                            <% else  %>
                                <p class="tag is-warning">予約できませんでした</p>
                            <% end  %>

                        </td>

                        <td>
                            <%= link_to room_path(trip.room), data: { turbolinks: false} do %>                                
                                <%= image_tag room_cover(trip.room), class: "image is-64x64" %>
                                <%= trip.room.listing_name %>
                            <% end %>
                        </td>

                        <td style="padding-top: 30px;">
                            <%= link_to user_path(trip.room.user), class: "tootip" do %>
                                <figure class="image is-48x48">
                                    <%= image_tag avatar_url(trip.room.user), class: "is-rounded" %>
                                </figure>
                                <%= trip.room.user.full_name %>
                            <% end %>
                        </td>

                        <td style="padding-top: 30px;">
                            宿泊日:<%= I18n.l(trip.start_date, format: :full_date) %><br/>
                            ご出発:<%= I18n.l(trip.end_date, format: :full_date) %>
                        </td>

                        <td style="padding-top: 30px;"><%= number_to_currency(trip.total) %></td>

                        <!-- アクション -->
                        <td style="padding-top: 30px;">
                            <%= render partial: "reviews/guest_form", locals: {reservation: trip} if trip.Approved? %>
                        </td>

                    </tr>
                <% end %>
            </tbody>
        </table>


    </div>
</section>



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

ステータス
ステータス



[39]ステータス表示<< [ホームに戻る] >> [41]クレジットカード決済 | Stripe(ストライプ)