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

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

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

[21]部屋ビュー作成<< [ホームに戻る] >> [23]アクションテキスト


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


コマンド
yarn add dropzone@5.5.1


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


記述追加 app\assets\stylesheets\application.scss(23行目)

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



app\assets\stylesheets\application.scss

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

 @import 'bulma';
 @import 'bulma-extensions';

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

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



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


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

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

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

$(document).ready(() => {
    $('.toggle').on('click', (e) => {
        e.stopPropagation();
        e.preventDefault();
        $('#' + e.target.getAttribute('aria-controls')).toggleClass('is-hidden');
    })
})

// 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」ファイルを以下のように編集します。


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

     <% if !@room.photos.blank? %>
      &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><i class="fa fa-check"></i></span>
    <% end %>



2.37行目に「&& !@room.photos.blank?」の記述を追加します。

<% is_ready = !@room.active && !@room.price.blank? && !@room.listing_name.blank? && !@room.address.blank? && !@room.photos.blank? %>



app\views\rooms\_room_menu.html.erb

<ul class="sidebar-list">
  <li class="sidebar-item">
    <%= link_to "お部屋の概要", listing_room_path, class: "sidebar-link active" %>
    &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><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? %>
      &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><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? %>
      &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><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? %>
      &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><i class="fa fa-check"></i></span>
    <% end %>
  </li>
  <li class="sidebar-item">
    <%= link_to "付属設備", amenities_room_path, class: "sidebar-link active" %>
    &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><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? %>
      &nbsp;&nbsp;<span class="pull-right text-babu" style="color: red;"><i class="fa fa-check"></i></span>
    <% end %>
  </li>
</ul>
<br/>
<br/>
<% 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: "button is-danger", disabled: !is_ready %>
<% end %>



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


1.記述追加 app/views/rooms/photo_upload.html.erb(30行目)

<div class="field">
    <label for="" class="label">お部屋の写真をアップロード</label>
    <div class="control">
        <div class="m-b-20">
            <div class="dropzone" id="myDropzone"  style="height: 200px; width: 600px;" action="/rooms/<%= @room.id %>/upload_photo"></div>
        </div>

        <div class="columns is-multiline">
            <% @room.photos.each do |photo| %>
                <div class="column is-one-fifth">
                    <div class="card is-image">
                        <div class="card-image">
                            <%= link_to 'Remove', delete_photo_room_url(photo_id: photo.id, id: @room.id), 
                                    method: :delete,
                                    data: { confirm: "本当に削除してよろしいですか?" },
                                    class: "delete delete-file is-pulled-right",
                                    style: "z-index: 100"  %>

                            <figure class="image is-4by3">
                                <%= image_tag url_for(photo) %>
                            </figure>
                        </div>
                    </div>
                </div>

            <% end %>
        </div>
    </div>
</div>



2.記述追加 app/views/rooms/photo_upload.html.erb(71行目)

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



app/views/rooms/photo_upload.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">
                                <!--写真アップロードの記述 -->

                                    <div class="field">
                                        <label for="" class="label">お部屋の写真をアップロード</label>
                                        <div class="control">
                                            <div class="m-b-20">
                                                <div class="dropzone" id="myDropzone"  style="height: 200px; width: 600px;" action="/rooms/<%= @room.id %>/upload_photo"></div>
                                            </div>

                                            <div class="columns is-multiline">
                                                <% @room.photos.each do |photo| %>
                                                    <div class="column is-one-fifth">
                                                        <div class="card is-image">
                                                            <div class="card-image">
                                                                <%= link_to 'Remove', delete_photo_room_url(photo_id: photo.id, id: @room.id), 
                                                                        method: :delete,
                                                                        data: { confirm: "本当に削除してよろしいですか?" },
                                                                        class: "delete delete-file is-pulled-right",
                                                                        style: "z-index: 100"  %>

                                                                <figure class="image is-4by3">
                                                                    <%= image_tag url_for(photo) %>
                                                                </figure>
                                                            </div>
                                                        </div>
                                                    </div>

                                                <% end %>
                                            </div>
                                        </div>
                                    </div>

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

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

<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


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

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



[21]部屋ビュー作成<< [ホームに戻る] >> [23]アクションテキスト