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

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

Rails6.0 | 民泊予約サイトの構築 | 23 | アクションテキスト

[22]写真アップロード(dropzone)<< [ホームに戻る] >> [24]写真カルーセル表示


アクションテキストをインストールします。


コマンド
rails action_text:install


マイグレーション適用
rails db:migrate


「app\models\room.rb」ファイルを以下の内容に更新します。


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

has_rich_text :description



app\models\room.rb

class Room < ApplicationRecord

  belongs_to :user

  has_many_attached :photos
  has_rich_text :description

  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\views\rooms\description.html.erb」ファイルを更新します。


32行目から37行目の記述を以下の記述に置き換えます。

<div class="row">
    <div class="field">
        <label for="" class="label">説明</label>
        <%= f.rich_text_area :description, rows: 50, cols: 50 %>
    </div>
</div>



記述変更 app\views\rooms\description.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="row">
                                            <div class="form-group">
                                            <label>お部屋の名前</label>
                                            <%= f.text_field :listing_name, placeholder: "お部屋の名前", class: "input", required: true, id: "autoaddress" %>
                                            </div>
                                        </div>
                                        <br/>

                                        <div class="row">
                                            <div class="field">
                                                <label for="" class="label">説明</label>
                                                <%= f.rich_text_area :description, rows: 50, cols: 50 %>
                                            </div>
                                        </div>
                                        
                                        <br/>
                                        <div class="text-center">
                                        <%= f.submit "保存", class: "button is-primary" %>
                                        </div>
 
                                    <% end %>
                                </div>
                            </div>
                        </div>
                    </article>
                </div>
            </div>
        </div>
    </div>
</section>



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


記述追加 app\controllers\rooms_controller.rb
76行目に「, :description」の記述を追加しています。

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



リッチテキストの中に画像をアップロードするにはアマゾンS3のアクセス許可の設定をしなければなりません。
アクセス許可のタブの下部にある「Cross-Origin Resource Sharing (CORS)」の項目に以下の記述を追加して保存します。

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]



画像のアップロードはこれでできるのですが、表示させるには「mini_magick」と「image_processing」をインストールする必要があります。
GemFileに以下の記述を追加して下さい。


記述追加 GemFile(69行目)

gem "mini_magick"
gem 'image_processing', '~> 1.2'



GemFile

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.6'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# 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.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

# Bulma
gem 'bulma-rails', '~> 0.7.4'
gem 'bulma-extensions-rails', '~> 1.0.30'

# デバイス
gem 'devise'

# 日本語化
gem 'rails-i18n'

# アマゾンS3
gem "aws-sdk"

# アクションテキスト画像表示
gem "mini_magick"
gem 'image_processing', '~> 1.2'



コマンド
bundle


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

リッチテキスト
リッチテキスト



↓↓クリックして頂けると励みになります。


[22]写真アップロード(dropzone)<< [ホームに戻る] >> [24]写真カルーセル表示