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

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

Rails7.1 | 仕事売買アプリ作成 | 37 | ActionText

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



36 | raty-js】 << 【ホーム】 >> 【38 | SQLによる検索機能実装



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

Gemfileに「mini_magick」と「image_processing」のgemを記述します。
これにより画像表示もできるようになります。
image_processingはActive Storageでも使うためすでに入っていますので、mini_magickのみ追加します。

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



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


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


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


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


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

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


モデル



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

has_rich_text :description



記述追加 【app/models/gig.rb】11行目

class Gig < ApplicationRecord
  belongs_to :user
  belongs_to :category

  has_many :pricings
  has_many :orders
  has_many :reviews
  
  has_many_attached :photos
  
  has_rich_text :description

  accepts_nested_attributes_for :pricings

  validates :title, presence: { message: '空白にはできません' }

  def average_rating
    reviews.count == 0 ? 0 : reviews.average(:stars).round(1)
  end
    
end


コントローラー



追加したアクションテキストのカラムに保存できるよう、gigコントローラーのパミッションに追加します。
「app/controllers/gigs_controller.rb」ファイルの119行目を以下の記述に変更します。
「:description, 」の記述を追加しています。


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

    if @step == 3 && gig_params[:description].blank?
      return redirect_to request.referrer, flash: {error: "詳細を空白にすることはできません"}
    end

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

      if @gig.description.blank?
        return redirect_to edit_gig_path(@gig, step: 3), flash: {error: "詳細を空白にすることはできません"}
      elsif @gig.photos.blank?
        return redirect_to edit_gig_path(@gig, step: 4), flash: {error: "写真がありません"}
      end



3.記述追加 【app/controllers/gigs_controller.rb】119行目

  def gig_params
    params.require(:gig).permit(:title, :video, :summary, :description, :active, :category_id, :has_single_pricing, :photos, 
                                pricings_attributes: [:id, :title, :description, :delivery_time, :price, :pricing_type])
  end



記述追加 【app/controllers/gigs_controller.rb】119行目

class GigsController < ApplicationController
 
  protect_from_forgery except: [:upload_photo]
  before_action :authenticate_user!, except: [:show]
  before_action :set_gig, except: [:new, :create]
  before_action :is_authorised, only: [:edit, :update, :upload_photo, :delete_photo]
  before_action :set_step, only: [:update, :edit]
  

  def new
    @gig = current_user.gigs.build
    @categories = Category.all
  end

  def create
    @gig = current_user.gigs.build(gig_params)

    if @gig.save
      @gig.pricings.create(Pricing.pricing_types.values.map{ |x| {pricing_type: x} })
      redirect_to edit_gig_path(@gig), notice: "保存しました"
    else
      redirect_to request.referrer, flash: { error: @gig.errors.full_messages }
    end
  end

  def edit
    @categories = Category.all
  end

  def update

    if @step == 2
      gig_params[:pricings_attributes].each do |index, pricing|
        if @gig.has_single_pricing && pricing[:pricing_type] != Pricing.pricing_types.key(0)
          next;
        else
          if pricing[:title].blank? || pricing[:description].blank? || pricing[:delivery_time].blank? || pricing[:price].blank?
            return redirect_to request.referrer, flash: {error: "価格が無効です"}
          end
        end
      end
    end

    if @step == 3 && gig_params[:description].blank?
      return redirect_to request.referrer, flash: {error: "詳細を空白にすることはできません"}
    end

    if @step == 4 && @gig.photos.blank?
      return redirect_to request.referrer, flash: {error: "写真がありません"}
    end

    if @step == 5
      @gig.pricings.each do |pricing|
        if @gig.has_single_pricing && !pricing.basic?
          next;
        else
          if pricing[:title].blank? || pricing[:description].blank? || pricing[:delivery_time].blank? || pricing[:price].blank?
            return redirect_to edit_gig_path(@gig, step: 2), flash: {error: "価格が無効です"}
          end
        end
      end

      if @gig.description.blank?
        return redirect_to edit_gig_path(@gig, step: 3), flash: {error: "詳細を空白にすることはできません"}
      elsif @gig.photos.blank?
        return redirect_to edit_gig_path(@gig, step: 4), flash: {error: "写真がありません"}
      end
    end

    if @gig.update(gig_params)
      flash[:notice] = "保存しました"
    else
      return redirect_to request.referrer, flash: {error: @gig.errors.full_messages}
    end

    if @step < 5
      redirect_to edit_gig_path(@gig, step: @step + 1)
    else
      redirect_to dashboard_path
    end

  end

  def show
    @photos = @gig.photos
    @categories = Category.all
    @i = 0
  end

  def upload_photo
    @gig.photos.attach(params[:file])
    render json: { success: true }
  end

  def delete_photo
    @image = ActiveStorage::Attachment.find(params[:photo_id])
    @image.purge
    redirect_to edit_gig_path(@gig, step: 4)
  end

  private

  def set_step
    @step = params[:step].to_i > 0 ? params[:step].to_i : 1
    if @step > 5
      @step = 5
    end
  end

  def set_gig
    @gig = Gig.find(params[:id])
  end

  def is_authorised
    redirect_to root_path, alert: "あなたには権限がありません。" unless current_user.id == @gig.user_id
  end

  def gig_params
    params.require(:gig).permit(:title, :video, :summary, :description, :active, :category_id, :has_single_pricing, :photos, 
                                pricings_attributes: [:id, :title, :description, :delivery_time, :price, :pricing_type])
  end
end


ビュー



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

<%= f.rich_text_area :description, class: "form-control" %>



記述変更 【app/views/gigs/_step3.html.erb】11行目

<% if @step == 3 %>
    <div class="card mb-2">
        <div class="card-body">
            <label class="label">Youtube共有リンク</label>
            <p>【https://youtu.be/ここを入力】</p>
            <%= f.text_field :video, autocomplete: "YoutubeのURI", class: "form-control" %>
        </div>
    </div>
    <div class="mt-4 mb-4">
            <label class="label font2">仕事の内容</label>
            <%= f.rich_text_area :description, class: "form-control" %>
    </div>
    <div class="mt-4 mb-4">
        <%= link_to '戻る', edit_gig_path(@gig, step: @step - 1), class: "btn btn-secondary" %>
        <%= f.submit '保存して続ける', class: "btn btn-danger", data: { turbo: false} %>
    </div>    
<% end %>



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

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


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



仕事詳細ページも「summary」の記述を「description」に変更します。


「app/views/gigs/show.html.erb」ファイルの94行目を以下に編集します。

<%= @gig.description %>



記述編集 【app/views/gigs/show.html.erb】98行目

<div class="container">
    <div class="mt-4 mb-4">
        <%= render 'shared/categories' %>
    </div>
    <div class="row">
        <!--  左側 -->
        <div class="col-md-4">
            <h5 class="font2 bg-light p-2" style="border-radius: 10px;"><%= @gig.title %></h5>
            <% if @gig.has_single_pricing %>
                <div class="card">
                    <div class="card-body">
                        <% @gig.pricings.each do |p| %>
                            <% if p.title %>
                                <div class="card-title font1">シングルプラン <span class="badge bg-danger"><%= number_to_currency(p.price) %></span></div>                            
                                <div class="font2"><%= p.description %></div>
                                <div><i class="far fa-clock"></i><span class="font2">期日:<%= p.delivery_time %></span></div>                                             
                                <div class="mt-4">
                                    <% if (!user_signed_in? && @gig.active) || (user_signed_in? && @gig.active && @gig.user_id != current_user.id) %>
                                        <%= form_for([@gig, @gig.orders.new]) do |f| %>
                                            <%= hidden_field_tag 'pricing_type', p.pricing_type %>
                                            <%= f.submit "仕事を依頼する(#{number_to_currency(p.price)})", class: "btn btn-danger w-100", data: {confirm: "本当によろしいですか?"} %>
                                        <% end %>    
                                    <% else %>
                                        <button class="btn btn-danger" disabled>ご利用できません</button>  
                                    <% end %>
                                </div>
                            <% end %>
                        <% end %>
                    </div>
                </div>
            <% else %>
                <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">          
                    <% Pricing.pricing_types.each do |key, value| %>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link <%= 'active' if value == 0 %>" id="pills-<%= key %>-tab" data-bs-toggle="pill" data-bs-target="#pills-<%= key %>" type="button" role="tab" aria-controls="pills-<%= key %>" aria-selected="<%= 'true' if value == 0 %><%= 'false' if !value == 0 %>">

                                <% if value == 0 %>
                                    ベーシック
                                <% elsif value == 1 %>
                                    スタンダード
                                <% else %>
                                    プレミアム
                                <% end %>

                            </button>
                        </li>
                    <% end %>
                </ul>
                <div class="tab-content" id="pills-tabContent">
                    
                    <% @gig.pricings.each do |p| %>
                        <div class="tab-pane fade <%= 'show active' if p.pricing_type == 'basic' %>" id="pills-<%= p.pricing_type %>" role="tabpanel" aria-labelledby="pills-<%= p.pricing_type %>-tab" tabindex="0">
                        
                            <div class="card">
                                <div class="card-body">
            
                                    <div class="card-title font1"><%= p.title %> <span class="badge bg-danger"><%= number_to_currency(p.price) %></span></div>
                                                                                                        
                                    
                                    <div class="font2"><%= p.description %></div>
                                    <div><i class="far fa-clock"></i><span class="font2">期日:<%= p.delivery_time %></span></div>                                             

                                    <div class="mt-4">
                                    <% if (!user_signed_in? && @gig.active) || (user_signed_in? && @gig.active && @gig.user_id != current_user.id) %>
                                        <%= form_for([@gig, @gig.orders.new]) do |f| %>
                                            <%= hidden_field_tag 'pricing_type', p.pricing_type %>
                                            <%= f.submit "仕事を依頼する(#{number_to_currency(p.price)})", class: "btn btn-danger w-100", data: {confirm: "本当によろしいですか?"} %>
                                        <% end %>    
                                    <% else %>
                                        <button class="btn btn-danger" disabled>ご利用できません</button>  
                                    <% end %>
                                    </div>
                                    
                                </div>
                            </div>
                        </div>
                    <% end %>
                </div>
            <% end %>           
        </div>

        <!--右側 -->
        <div class="col-md-8">
            <div class="card mt-4 mb-4">
                <div class="card-body">
                    <h5 class="font1">フリーランサー</h5>
                    <div class="mt-2">
                    <%= link_to user_path(@gig.user), style: "text-decoration:none;" do %>
                        <%= image_tag avatar_url(@gig.user), class: "bd-placeholder-img figure-img img-fluid rounded-pill", style: "width: 80px;" %>
                        <span class="font2 text-dark h4"><%= @gig.user.full_name %></span>
                    <% end %>
                    </div>
                    <div class="font2">
                        <%= @gig.description %>
                    </div>
                </div>
            </div>
            <!-- カルーセル表示 -->
            <div class="card">
                <div class="card-body">

                    <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
                        <div class="carousel-indicators">
                            <% @photos.each do |photo| %>
                                <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="<%= @i %>" class="<%= 'active' if photo.id == @photos[0].id %>" aria-current="true" aria-label="Slide <%= @i+1 %>"></button>
                                <% @i = @i +1 %>
                            <% end %>
                        </div>
                        <div class="carousel-inner">
                            <%  @gig.photos.each do |photo| %>
                                <div class="carousel-item <%= 'active' if photo.id == @photos[0].id %>">
                                    <%= image_tag url_for(photo), class: "d-block w-100", style: "border-radius: 10px;" %>
                                </div>
                            <% end %>
                        </div>
                        <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev">
                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                            <span class="visually-hidden">Previous</span>
                        </button>
                        <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next">
                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                            <span class="visually-hidden">Next</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Youtube表示 -->
            <% if @gig.video.present? %>
            <div class="card mt-4">
                <iframe height="360" src="https://www.youtube.com/embed/<%= @gig.video %>" allowfullscreen></iframe>
            </div>
            <% end %>
        </div>

    </div>
</div>



ブラウザを確認します。
新しく仕事を登録して表示を確認してください。
http://localhost:3000/gigs/8

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




36 | raty-js】 << 【ホーム】 >> 【38 | SQLによる検索機能実装





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