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

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

Rails6.1 | 仕事売買アプリ作成 | 40 | Pagination

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




39 | ホームページ】 << 【ホーム】 >> 【41 | Stripe



ページネーション(Pagination)は、ウェブサイトやアプリケーションで長いリストやコンテンツを複数のページに分割する方法です。
ページネーションを利用することにはいくつかの利点があります。
長いリストやコンテンツを一度に表示すると、ページが読み込みに時間がかかり、ユーザーが情報を見つけるのが難しくなります。
ページネーションを使用することで、コンテンツが小さなページに分割され、ユーザーがスムーズに移動し、必要な情報を見つけやすくなります。

Ruby on Railsでページネーションを実装するために、kaminari というページネーション用のジェム(Gem)を使用します。


「GemFile」に以下の記述を追加します。

gem 'kaminari', '~> 1.2', '>= 1.2.2'
gem 'bootstrap5-kaminari-views'



ターミナルで以下のコマンドを実行します。

bundle install


コントローラー



コントローラーのアクション内で、ページネーションを設定します。
「app\controllers\pages_controller.rb」ファイルに以下の記述を追加します。


記述追加 app\controllers\pages_controller.rb(4行目)

.page(params[:page]).per(8)



これは8アイテム以降は次のページに読み込ませるという設定になります。
記述追加 app\controllers\pages_controller.rb

class PagesController < ApplicationController

  def home
    @gigs = Gig.all.order("created_at desc").page(params[:page]).per(8)
  end
  
  def search
    @categories = Category.all
    @category = Category.find(params[:category]) if params[:category].present?
    @q = params[:q]
    @min = params[:min]
    @max = params[:max]
    @delivery = params[:delivery].present? ? params[:delivery] : "0"
    @sort = params[:sort].present? ? params[:sort] : "price asc"
    query_condition = []
    query_condition[0] = "gigs.active = true"
    query_condition[0] += " AND ((gigs.has_single_pricing = true AND pricings.pricing_type = 0) OR (gigs.has_single_pricing = false))"
    if !@q.blank?
      query_condition[0] += " AND gigs.title ILIKE ?"
      query_condition.push "%#{@q}%"
    end
    if !params[:category].blank?
      query_condition[0] += " AND category_id = ?"
      query_condition.push params[:category]
    end
    if !params[:min].blank?
      query_condition[0] += " AND pricings.price >= ?"
      query_condition.push @min
    end
    if !params[:max].blank?
      query_condition[0] += " AND pricings.price <= ?"
      query_condition.push @max
    end
    if !params[:delivery].blank? && params[:delivery] != "0"
      query_condition[0] += " AND pricings.delivery_time <= ?"
      query_condition.push @delivery
    end
    @gigs = Gig
                .select("gigs.id, gigs.title, gigs.user_id, MIN(pricings.price) AS price")
                .joins(:pricings)
                .where(query_condition)
                .group("gigs.id")
                .order(@sort)
  end
end


ビュー



「app/views/pages/home.html.erb」ファイルの24行目に以下の記述を追加します。

<%= paginate @gigs, theme: 'bootstrap-5' %>



記述追加 【app/views/pages/home.html.erb】92行目

<div class="container">
    <div class="has-bg-img mb-4 p-4">
        <h2 class="font2 text-light mb-4">
            フリーランサーが登録する仕事があります<br/>
            どんな仕事をお探しですか?
        </h2>
        <div class="input-group mb-3">
            <span class="input-group-text">
                <i class="fa fa-search"></i>                
            </span>
            <%= form_tag search_path, method: :get, class: "form-control" do %>
                    <%= text_field_tag 'q', '', class: "form-control", placeholder: "どんなお仕事をお探し?" %>
                </div>
                <div class="control">
                    <button class="btn btn-primary" type="submit">検索する</button>
                </div>
            <% end %>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <h2 class="font1">登録されている仕事</h2>
        <%= paginate @gigs, theme: 'bootstrap-5' %>
        <% @gigs.each do |gig| %>
            <div class="col-md-3">
                <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">
                        <span class="star-review">
                            <i class="fa fa-star text-warning"></i>
                            <%= gig.average_rating %>
                            <span class="has-text-primary">(<%= gig.reviews.count %>)</span>
                        </span>
                        
                        <%= link_to gig_path(gig), data: { turbolinks: false} do %>
                            <h5 class="card-title">
                                <span class="btn btn-light"><%= gig.title %></span>
                            </h5>
                        <% end %>                       

                        <div>
                            <%= 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: 30px;" %>
                                <span class="font2 text-dark"><%= gig.user.full_name %></span>
                            <% end %>
                        </div>    
                    </div>
                </div>
            </div>
        <% end %>
    </div>
</div>



表示を確認します。
http://localhost:3000/
ページネーションが機能しますが、見た目がデフォルトの状態になっています。

ページネーション
ページネーション



カスタマイズします。
「app/assets/stylesheets/application.scss」ファイルに記述を追加して、デザインをカスタマイズします。

  /*ページネーション自体のデザイン*/
.pagination>li>a {          
  color: #000000;   /*文字の色を変える*/
}

/* 表示しているページ番号のデザイン */
.pagination>.active>a {     
  background: #3d3f41;     /*背景の色を変える*/
}

/*ホバー時のデザイン*/
.pagination>li>a:hover {        
  background: #696b6d;     /*背景の色を変える*/
  color: #ffffff;   /*文字の色を変える*/
}



記述追加 【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
 */


// フォント
body * {
    font-family: Kosugi Maru;
}

.font1 {
    font-family: Rampart One;
}

.font2 {
    font-family: Kaisei Opti;
}

//アバター オンライン
.avatar {
    position: relative;
    display: inline-block;
    &::before {
      content: "";
      position: absolute;
      bottom: 1px;
      left: 38px;
      width: 10px;
      height: 10px;
      border-radius: 100%;
      border: 1px solid white;
    }
    &.online:before {
      background-color: #1dbf73;
    }
    &.offline:before {
      background-color: gray;
    }
}

//ホームページ用
.has-bg-img {
  background: url("/assets/home/background01.jpg") center center;
  background-size: cover;
}

  /*ページネーション自体のデザイン*/
  .pagination>li>a {          
    color: #000000;   /*文字の色を変える*/
  }
  
  /* 表示しているページ番号のデザイン */
  .pagination>.active>a {     
    background: #3d3f41;     /*背景の色を変える*/
  }
  
  /*ホバー時のデザイン*/
  .pagination>li>a:hover {        
    background: #696b6d;     /*背景の色を変える*/
    color: #ffffff;   /*文字の色を変える*/
  }



表示を確認します。
CSSが適用されて、見た目が変わりました。
http://localhost:3000/

ページネーションCSS適用
ページネーションCSS適用



39 | ホームページ】 << 【ホーム】 >> 【41 | Stripe



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