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

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

Ruby on Rails6.0 | 空き部屋を登録・予約・決済できるWebサイトを作成する 74 | Bootstrap | 写真アップロード(dropzone)

「22 | 写真アップロード(dropzone)」の内容をBootstrapの記述で書き換えます。


複数の画像をアップロードできるようにします。
まずは「doropzone」のインストールをします。


コマンド
yarn add dropzone@5.5.1


「app\assets\stylesheets\application.scss」ファイルに以下の記述を追加します。


記述追加 app/javascript/stylesheets/application.scss(6行目)

@import 'dropzone/dist/basic.css';
@import 'dropzone/dist/dropzone.css';



app/javascript/stylesheets/application.scss

@import '~bootstrap/scss/bootstrap';

@import 'noty/lib/noty';
@import 'noty/lib/themes/sunset';

@import 'dropzone/dist/basic.css';
@import 'dropzone/dist/dropzone.css';

//アバター オンライン
.avatar {
  position: relative;
  display: inline-block;
  &::before {
    content: '';
    position: absolute;
    top: -10px;
    right: -50px;
    width: 10px;
    height: 10px;
    border-radius: 100%;
    border: 1px solid white;
  }
  &.online:before {
    background-color: #1dbf73;
  }
  &.offline:before {
    background-color: gray;
  }
}

//ホームページ用
.has-bg-img {
  background: url('/assets/home/background01.jpg') center center;
  background-size: cover;
}

//ナビゲーションバー
.navh1 {
    font-size: 1.6rem;
}

.collapse {
    margin-right: 80px;
}

//フォント
body {
    font-family: 'Kosugi Maru', 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 {

    border-radius: 5px;
    font-weight: bold;
    padding: 9px 27px;
  }
  
  .btn-small {
    padding: 5px 15px;
    margin-top: 15px;
  }
  
//   .btn:hover, .btn:focus {
//     color: rgba(80, 78, 78, 0.747);
//   }
  
  .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;
  }
  
  
  // フォーム
  .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: 5px;
    padding: 10px;
    appearance: none;
    -moz-appearance: none; /* Firefox */
    -webkit-appearance: none; /* Safari & Chrome */
  }
  
  .select:before {
    content: '\25bc';
    font-size: 0.8em;
    position: absolute;
    color: #00A699;
    top: 45px;
    right: 18px;
    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;
  }
  



「app\javascript\packs\application.js」ファイルに以下の記述を追加します。


記述追加 app\javascript\packs\application.js(17行目)

window.Dropzone = require("dropzone")



app\javascript\packs\application.js

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

require("jquery")

import 'bootstrap';
import '../stylesheets/application';

window.Noty = require("noty")
window.Dropzone = require("dropzone")


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

require("trix")
require("@rails/actiontext")



「app\models\room.rb」ファイルに以下の記述を追加します。


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

has_many_attached :photos



app\models\room.rb

class Room < ApplicationRecord

  belongs_to :user

  has_many_attached :photos

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



「app\controllers\rooms_controller.rb」ファイルを以下の手順で編集していきます。


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

protect_from_forgery except: [:upload_photo]



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

before_action :is_authorised, only: [:listing, :pricing, :description, :photo_upload, :amenities, :location, :update]



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

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



4.59行目に「upload_photo()」メソッド、「delete_photo()」メソッドを追加します。

  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



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

    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



記述更新 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
  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

  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)
    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

  end



ルートの設定を以下の内容に更新します。


記述更新 config\routes.rb(25行目)

      delete :delete_photo
      post :upload_photo



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'
  
  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'
      delete :delete_photo
      post :upload_photo
    end
  end

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end



「app\views\rooms\_room_menu.html.erb」ファイルを以下のように編集します。


app\views\rooms\_room_menu.html.erb

<br/>
<div class="row" style="margin-left: 50px;">

        <div class="card text-center">

                <div class="card-body">
                <br/>

                <ul class="sidebar-list" style="margin-left: 30px; margin-right: 30px;">
                <li class="sidebar-item">
                  <%= link_to "お部屋の概要", listing_room_path, class: "sidebar-link active" %>
                  <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
                </li>
                <li class="sidebar-item">
                  <%= link_to "1泊の宿泊価格", pricing_room_path, class: "sidebar-link active" %>
                  <% if !@room.price.blank? %>
                    <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
                  <% end %>
                </li>
                <li class="sidebar-item">
                  <%= link_to "お部屋の名前と説明", description_room_path, class: "sidebar-link active" %>
                  <% if !@room.listing_name.blank? %>
                    <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
                  <% end %>
                </li>
                <li class="sidebar-item">
                    <%= link_to "お部屋の写真", photo_upload_room_path, class: "sidebar-link active", data: { turbolinks: false} %>
                    <% if !@room.photos.blank? %>
                        <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
                    <% end %>                  
                </li>
                <li class="sidebar-item">
                  <%= link_to "付属設備", amenities_room_path, class: "sidebar-link active" %>
                  <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
                </li>
                <li class="sidebar-item">
                  <%= link_to "お部屋の住所", location_room_path, class: "sidebar-link active" %>
                  <% if !@room.address.blank? %>
                    <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
                  <% end %>
                </li>
              </ul>
              <hr/>
              <% is_ready = !@room.active && !@room.price.blank? && !@room.listing_name.blank? && !@room.address.blank? && !@room.photos.blank? %>
              <%= form_for @room do |f| %>
                <%= f.hidden_field :active, value: true %>
                <%= f.submit "公開する", id: "publish_button", class: "btn btn-danger btn-block", disabled: !is_ready %>
              <% end %>


                </div>
        </div>      
</div>



「app/views/rooms/photo_upload.html.erb」ファイルに記述を追加します。


app/views/rooms/photo_upload.html.erb

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

        <div class="row">
            <div class="col-sm-9">
                <br/>
                <div class="card text-center">
                    <h4 class="card-header text-center">お部屋の写真 登録</h4>
                    <div class="card-body" style="margin-left: 50px;">
                        <br/>

                        <!--写真アップロードの記述 -->
                        <div class="dropzone" id="myDropzone"  style="height: 200px; width: 600px;" action="/rooms/<%= @room.id %>/upload_photo"></div>

                        <br/>
                        <div class="container" style="margin-left: 20px;">
                            <div class="row">

                                <% @room.photos.each do |photo| %>
        
                                    <div class="col-md-3">
                                        <figure>
                                            <%= image_tag url_for(photo),  style: "width: 100%;" %>
                                        </figure>
                                    
                                        <%= link_to '削除', delete_photo_room_url(photo_id: photo.id, id: @room.id), 
                                                method: :delete,
                                                data: { confirm: "本当に削除してよろしいですか?" },
                                                style: "z-index: 100; margin-top: -15px; margin-bottom: 20px; font-size: 10px;",
                                                class: "btn btn-outline-danger btn-sm"  %>
                                    </div>
        
                                <% end %>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    Dropzone.options.myDropzone = {
        paramName: "file",
        maxFilesize: 2,
        acceptedFiles: "image/*",
        init: function() {
            this.on('complete', function (file) {
                location.reload();
            })
        }
    }
</script>



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


写真のアップロードができます。
複数の写真も同時にアップロードできます。

画像のアップロードと削除
画像のアップロードと削除