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

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

【民泊5.1】【Windows】収益チャート

記述追加 GemFile(96行目)

gem 'chartkick', '~> 2.2.4'



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'

# Stripe決済
gem 'stripe', '~> 3.0.0'
gem 'rails-assets-card', source: 'https://rails-assets.org'

# Stripeコネクト
gem 'omniauth', '~> 1.6'
gem 'omniauth-stripe-connect', '~> 2.10.0'

# 収益チャート
gem 'chartkick', '~> 2.2.4'



コマンド
bundle


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

//= require Chart.bundle
//= require chartkick



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 card
//= require Chart.bundle
//= require chartkick
//= require turbolinks
//= require_tree .



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

  scope :current_week_revenue, -> (user) {
    joins(:room)
    .where("rooms.user_id = ? AND reservations.updated_at >= ? AND reservations.status = ?", user.id, 1.week.ago, 1)
    .order(updated_at: :asc)
  }



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

  scope :current_week_revenue, -> (user) {
    joins(:room)
    .where("rooms.user_id = ? AND reservations.updated_at >= ? AND reservations.status = ?", user.id, 1.week.ago, 1)
    .order(updated_at: :asc)
  }

end



「app\controllers」フォルダに「revenues_controller.rb」ファイルを新規作成してください。


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

class RevenuesController < ApplicationController
    before_action :authenticate_user!
  
    def index
        @reservations = Reservation.current_week_revenue(current_user)
  
        @this_week_revenue = @reservations.map {|r| {r.updated_at.strftime("%Y-%m-%d") => r.total} }
                                        .inject({}) {|a,b| a.merge(b){|_,x,y| x + y}}

        @this_week_revenue = Date.today().all_week.map{ |date| [date.strftime("%a"), @this_week_revenue[date.strftime("%Y-%m-%d")] || 0 ] }
    end
  end



記述追加 config\routes.rb
43行目に「resources :revenues, only: [:index]」の記述追加

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"
  get '/payment_method' => "users#payment"
  get '/payout_method' => "users#payout"

  post '/add_card' => "users#add_card"

  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]
    resources :calendars
  end

  resources :guest_reviews, only: [:create, :destroy]
  resources :host_reviews, only: [:create, :destroy]

  resources :revenues, only: [:index]

  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: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end



「app\views」フォルダに「revenues」フォルダを新規作成します。
作成した「revenues」フォルダに「index.html.erb」ファイルを新規作成してください。



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

<div class="row">
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading">今週の収益</div>
      <div class="panel-body">
        <div class="container text-center">
          <% if @reservations.blank? %>
              <h3>今週はまだ収益がありません。</h3><br/>
          <% else %>
              <%= column_chart @this_week_revenue, colors: ["#00A699"] %>
          <% end %>
        </div>
      </div>
    </div>
  </div>
</div>



ブラウザ確認


http://localhost:3000/revenues


一週間分の収益をグラフで表示します。


一週間分の収益グラフ
一週間分の収益グラフ