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

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

Rails6.1 | 仕事売買アプリ作成 | 29 | Application Helper

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


28 | trestle】 << 【ホーム】 >> 【30 | Order


RailsのApplication Helper(アプリケーションヘルパー)は、Ruby on Railsフレームワークで使用される便益的なメソッドや関数を定義するためのユーティリティクラスです。
これらのヘルパーメソッドは、ビュー(View)やコントローラー(Controller)で共通のコードを抽象化し、再利用性を高めるために使用されます。
主にビューで使用され、ビューで表示のロジックやデータフォーマットを簡素化し、DRY(Don't Repeat Yourself)の原則に従います。

Application Helperは通常、app/helpers/application_helper.rbというファイルに定義されます。
このファイルに定義したヘルパーメソッドは、全てのビューで利用可能です。


カードで仕事の写真を表示させる際に使うヘルパーを作成します。
「app\assets\images」フォルダに「icon_default_image.jpg」ファイルを保存しておいてください。


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

def gig_cover(gig)
    if gig.photos.attached?
        url_for(gig.photos[0])
    else
        ActionController::Base.helpers.asset_path('icon_default_image.jpg')
    end
end   



記述追加 app\helpers\application_helper.rb(11行目)

module ApplicationHelper
    def avatar_url(user)
        if user.avatar.attached?
            url_for(user.avatar)
        elsif user.image?
            user.image
        else
            ActionController::Base.helpers.asset_path('icon_default_avatar.jpg')
        end
    end
    
    def gig_cover(gig)
        if gig.photos.attached?
            url_for(gig.photos[0])
        else
            ActionController::Base.helpers.asset_path('icon_default_image.jpg')
        end
    end
        
end



作成したヘルパーを使って、ビューを編集していきます。
まずは仕事コントローラーのshowメソッドに以下の記述を追加します。
「app\controllers\gigs_controller.rb」ファイルの「show()」メソッドを以下のように編集します。

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



記述追加 【app\controllers\gigs_controller.rb】84行目

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[:summary].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.summary.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, :active, :category_id, :has_single_pricing, :photos, 
                                pricings_attributes: [:id, :title, :description, :delivery_time, :price, :pricing_type])
  end
end



「app\views\shared」フォルダに「_categories.html.erb」ファイルを新規作成します。


作成したレンダーファイルを以下のように編集します。
app\views\shared\_categories.html.erb(新規作成したファイル)

<div class="container mt-4 mb-4">
    <div class="card">
        <div class="card-body">
            <h5 class="badge bg-dark">カテゴリー</h5>
            <div>
                <% @categories.each do |item| %>
                <%= link_to "#{item.name}", root_path, class: "btn btn-light font2" %>
                <% end %>
            </div>
        </div>
    </div>
</div>



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


記述編集 【app\views\gigs\show.html.erb】

<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) %>
                                        <button class="btn btn-danger w-100">依頼する (<%= number_to_currency(p.price) %>)</button>  
                                    <% 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">
                    <h5 class="font2 bg-light p-2" style="border-radius: 10px;"><%= @gig.title %></h5>            
                    <% 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) %>
                                        <button class="btn btn-danger w-100">依頼する (<%= number_to_currency(p.price) %>)</button>  
                                    <% 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.summary %>
                    </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>



ブラウザを確認します。
写真はBootstrapのカルーセル表示を利用しています。
http://localhost:3000/gigs/1


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


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



ダッシュボードを更新します。
「app/views/users/dashboard.html.erb」ファイルを編集します。


記述編集 【app/views/users/dashboard.html.erb】

<div class="container mt-4 mb-4">
    <div class="row">
        <!-- 左側 -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <!-- アバター -->
                    <%= image_tag avatar_url(current_user), class: "img-fluid img-thumbnail rounded-pill" %>
                    <h4 style="margin-left: 5.5rem;"><%= current_user.full_name %></h4>
                    <!-- 画像アップロードボタン -->
                    <button class="btn btn-dark text-light w-100" type="button" data-bs-toggle="collapse" data-bs-target="#collapse1" aria-expanded="false" aria-controls="collapse1">
                        <i class="fa-solid fa-cloud-arrow-up"></i>アバター画像アップロード
                    </button>
                    <div class="collapse" id="collapse1">
                    <div class="card card-body">
                        <%= form_for :user, url: users_edit_url(current_user), action: :update, method: :post do |f| %>
                            <%= f.file_field :avatar, class: "input-group-text", onchange: "this.form.submit();" %>
                        <% end %>   
                    </div>
                </div>
                <hr/>
                登録:<%= I18n.l(current_user.created_at, format: :full_date) %>
                <hr/>
                <div type="button" data-bs-toggle="collapse" data-bs-target="#collapse2" aria-expanded="false" aria-controls="collapse2">

                    <% if current_user.status %>
                        <span class="btn btn-success"><i class="toggle far fa-edit"></i>オンライン</span>
                    <% else %>
                        <span class="btn btn-secondary"><i class="toggle far fa-edit"></i>オフライン</span>
                    <% end %>                
                
                </div>
                <div class="collapse" id="collapse2">
                    <div class="card card-body">

                        <%= form_for :user, url: users_edit_url(current_user), action: :update, method: :post do |f| %>
                            <%= f.select(:status, options_for_select([["オンライン", true], ["オフライン", false]]), {}, {class: "custom-select"}) %>                        
                            <%= f.submit "保存", class: "btn btn-dark" %>
                        <% end %>

                    </div>
                </div>
                <hr/>
                <div class="h5"><%= current_user.about %></div>
                <button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapse3" aria-expanded="false" aria-controls="collapse3">
                    自己紹介編集
                </button>

                <div class="collapse" id="collapse3">
                    <div class="card card-body">
                        <%= form_for :user, url: users_edit_url(current_user), action: :update, method: :post do |f| %>
                            <div><%= f.text_area :about, autofocus: true, autocomplete: 'form'%></div>
                            <%= f.submit "保存", class: "btn btn-dark" %>
                        <% end %>                        
                    </div>
                </div>
                <hr />
                <!-- 電話番号 -->
                <div>
                    <% if !current_user.phone_number.blank? %>
                        <span class="pull-right icon-babu"><i class="far fa-check-circle" style="color:green;"></i></span>&nbsp;&nbsp;電話番号
                    <% else %>
                        <div class="text-danger">電話番号が登録されていません</div>
                        <%= link_to  "電話番号登録", edit_user_registration_path, class: "btn btn-danger" %>
                    <% end %>                    
                    </div>       
                    
                </div>
            </div>
        </div>
        <!-- 右側 -->
        <div class="col-md-8">

            <!-- お知らせ -->
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">お知らせ</h5>
                    <h6 class="card-subtitle mb-2 text-body-secondary">
                    </h6>
                    <p class="card-text">
                    </p>    
                </div>
            </div>

            <!-- 登録している仕事 -->
            <div class="card mt-2">
                <div class="card-body">
                    <h5 class="card-title">登録している仕事</h5>

                    <div class="row">
                        <% current_user.gigs.each do |gig| %>
                            <% if gig.active? %>
                                <div class="col-md-4">
                                    <div class="card mb-2">
                                    <%= link_to gig_path(gig), data: { turbolinks: false} do %>
                                        <%= image_tag gig_cover(gig), style: "width: 100%;", class: "card-img-top" %>
                                    <% end %>                                    
                                        <div class="card-body">
                                            <%= link_to gig_path(gig), data: { turbolinks: false} do %>
                                                <h5 class="card-title">
                                                    <span class="btn btn-light"><%= gig.title %></span>
                                                </h5>
                                            <% end %>
                                            <div class="card-text" style="margin-left: 0.5rem;">
                                                <p><%= gig.summary %></p>          
                                                <%= link_to edit_gig_path(gig), class: "btn btn-outline-primary w-100 mb-4" do %>
                                                    登録内容編集
                                                <% end %>
                                              
                                            </div>                             
                                        </div>
                                    </div>
                                </div>
                            <% end %>
                        <% end %>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



ブラウザで確認します。
http://localhost:3000/dashboard

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


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



ユーザー情報紹介ページを更新します。
「app/views/users/show.html.erb」ファイルを編集します。


記述編集 【app/views/users/show.html.erb】

<div class="container mt-4 mb-4">
    <div class="row">
        <!-- 左側 -->
        <div class="col-md-4 mb-4">
            <div class="card">
                <div class="card-body">

                    <!-- ステータス -->
                    <div>
                        <% if @user.status %>
                            <span class="badge bg-success"><i class="fa-regular fa-bell"></i>オンライン</span>
                        <% else %>
                            <span class="btn btn-secondary"><i class="fa-regular fa-bell-slash"></i>オフライン</span>
                        <% end %>                                   
                    </div>                
                    <!-- アバター -->
                    <%= image_tag avatar_url(@user), class: "img-fluid img-thumbnail rounded-pill" %>
                    <h4 class="text-center"><%= @user.full_name %></h4>   
                    
                    <!-- 自己紹介 -->
                    <div class="h5 text-center"><%= @user.about %></div>                           
                </div>
            </div>       

        </div>
        <!-- 右側 -->
        <div class="col-md-8">

            <!-- 登録している仕事 -->
            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title font1"><%= @user.full_name %>さんが登録している仕事</h5>

                    <div class="row">
                        <% @user.gigs.each do |gig| %>
                            <% if gig.active? %>
                                <div class="col-md-4">
                                    <div class="card mb-2">
                                        <%= link_to gig_path(gig), data: { turbolinks: false} do %>
                                            <%= image_tag gig_cover(gig), style: "width: 100%;", class: "card-img-top" %>
                                        <% end %>                                    
                                        <div class="card-body">
                                            <%= link_to gig_path(gig), data: { turbolinks: false} do %>
                                                <h5 class="card-title">
                                                    <span class="btn btn-light"><%= gig.title %></span>
                                                </h5>
                                                <div class="badge bg-primary">
                                                    <% if gig.has_single_pricing%>
                                                        シングルプランのみ
                                                    <% else %>
                                                        3プラン
                                                    <% end %>
                                                </div>
                                            <% end %>                        
                                        </div>
                                    </div>
                                </div>
                            <% end %>
                        <% end %>
                    </div>
                </div>  
            </div>
            <!-- レビュー -->
            <div class="card">           
                <div class="card-body">
                    <h5 class="card-title"><%= @user.full_name %>さんへのレビュー</h5>
                    <h6 class="card-subtitle mb-2 text-body-secondary">
                    </h6>
                    <p class="card-text">
                    </p>    
                </div>
            </div>

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



ブラウザを確認します。
ユーザ情報の詳細を他のユーザも確認できます。
http://localhost:3000/users/2

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


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



ナビゲーションバーに「仕事を登録する」リンクを追加します。


記述追加 【app/views/shared/_navbar.html.erb】36行目

<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="/"><span class="font1">Gig Hub</span></a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <!-- もしログインしていなかったら-->
        <% if (!user_signed_in?) %>
        <li class="nav-item" style="margin-bottom: 0.1rem;">
          <span style="margin-left: 1rem;">
          <%= link_to  "新規登録", new_user_registration_path, class: "btn btn-danger" %>
          </span>
        </li>
        <li class="nav-item">
          <span style="margin-left: 1rem;">
            <%= link_to  "ログイン", new_user_session_path, class: "btn btn-success text-light" %>
          </span>
        </li>
      </ul>
      <!-- ログインしていたら -->
      <% else %>
      <ul class="navbar-nav" style="margin-left: 2rem;">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">

          <figure style="position:relative; top: 0.2rem;" class="avatar <%= current_user.status ? "online" : "offline" %>"></figure>  
          <%= image_tag avatar_url(current_user), class: "bd-placeholder-img figure-img img-fluid rounded-pill", style: "width: 40px; height: 30px;" %>          
            <%= current_user.full_name %>
          </a>
          <ul class="dropdown-menu">
            <li><%= link_to  "ダッシュボード", dashboard_path, class: "dropdown-item btn btn-lightt" %></li>
            <li><%= link_to  "ユーザ登録情報編集", edit_user_registration_path, class: "dropdown-item btn btn-light" %></li>
            <li><hr class="dropdown-divider"><span class="badge bg-danger" style="margin-left: 1rem;">フリーランサー</span></li>
            <li><%= link_to  "仕事を新規登録", new_gig_path, class: "dropdown-item btn btn-light" %></li>
            <li><hr class="dropdown-divider"><span class="badge bg-primary" style="margin-left: 1rem;">クライアント</span></li>
            <li><hr class="dropdown-divider"></li>
            <li><%= link_to  "ログアウト", destroy_user_session_path, method: :delete, class: "dropdown-item btn btn-light" %></li>
          </ul>
        </li>
      </ul>
      <% end %>

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



ブラウザを確認します。

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


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




28 | trestle】 << 【ホーム】 >> 【30 | Order


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