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

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

Rails7.1 | 民泊予約アプリ作成 | 22 | Action Text

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



21 | Amazon S3】 << 【ホーム】 >> 【23 | Autocompleteとgeocoderの利用



Ruby on Railsで利用できるAction Textを使えば、リッチテキストフィールドを簡単に統合できます。
Action Textを導入する手順を順を追って説明します。

GemfileにAction Textを追加します。

アップロードした画像を表示させるには「mini_magick」と「image_processing」のgemをインストールする必要があります。
「image_processing」はRails7.1のデフォルトでインストールされているので、「mini_magick」のみgemに追加します。

# action text
gem 'mini_magick', '~> 4.12'



ターミナルで以下のコマンドを実行して、Gemをインストールします。
コマンド
bundle


Action Textのインストールジェネレータを実行します。
ターミナルで以下のコマンドを実行します。
コマンド
rails action_text:install


このコマンドにより、Action Text用のマイグレーションファイルとJavascriptファイルが生成されます。


「app/javascript/application.js」ファイルを見てみると、「import "trix"」と「import "@rails/actiontext"」の記述が自動で追加されているのが分かります。
確認 【app/javascript/application.js】

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import 'bootstrap';
import 'fontawesome';

import "trix"
import "@rails/actiontext"



マイグレーションを実行して、データベースに必要なテーブルを作成します
コマンド
rails db:migrate


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

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


モデル



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

has_rich_text :description



記述追加 【app/models/room.rb】6行目

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


コントローラー



追加したアクションテキストのカラムに保存できるよう、roomコントローラーの記述を変更します。


1.記述追加 【app/controllers/rooms_controller.rb】7行目
「summary」を「description」に変更しています。

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



2.記述追加 【app/controllers/rooms_controller.rb】79行目

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)



記述追加 【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, :delete_photo, :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


ビュー



「app/views/rooms/description.html.erb」ファイルの20行目を以下の記述に変更します。

<%= f.rich_text_area :description, class: "w-100", style: "height: 10rem;" %>



記述変更 【app/views/rooms/description.html.erb】20行目

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

            <div class="card">
                <div class="card-body">
                <h4 class="mt-4 mb-4"><b>部屋の名前と説明</b></h4>

                    <%= form_for @room do |f| %>
                        <div class="mb-4">
                            <label>部屋の名前</label>
                            <%= f.text_field :listing_name, placeholder: "部屋の名前", class: "form-control w-100", required: true %>
                    </div>

                    <div class="mb-4">
                            <label>説明</label>
                            <%= f.rich_text_area :description, class: "w-100", style: "height: 10rem;" %>
                        </div>
                    <br/>
                    <div>
                        <%= f.submit "保存", class: "btn btn-danger w-100" %>
                    </div>
                    <% end %>
                
                </div>
            </div>
        </div>
    </div>
</div>



ブラウザを確認します。
リッチテキストが利用できるようになりました。
動作を確認してください。

PCレイアウト
PCレイアウト


モバイルレイアウト
モバイルレイアウト




21 | Amazon S3】 << 【ホーム】 >> 【23 | Autocompleteとgeocoderの利用





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