[Rails] Add page nation to table [For beginners]

Implement the following page nation

ページネーション.png

Note

The email address shown in the image is not real Bootstrap is applied to Rails

Reference: Using Bootstrap 4 with Rails App --Qiita

environment

Initial code

controller

app/controllers/users_controller.rb


###Above omitted###
def index
  @users = User.all
end
###The following is omitted###

View

erb:app/views/users/index.html.erb


<div class="mt-2 mb-2 mr-5 ml-5 pr-5 pl-5">
  <table class="table table-sm table-hover">
    <thead class="thead-dark">
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </thead>
  
    <tbody>
      <% @users.each do |user| %>
        <tr>
          <td><%= user.name %></td>
          <td><%= user.email %></td>
          <td><%= link_to 'Show', user %></td>
          <td><%= link_to 'Edit', edit_user_path(user) %></td>
          <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
      <% end %>
    </tbody>
  </table>
</div>

Initial screen and screen you want to realize

initial screen

All Users are displayed 初期画面.png

Screen you want to realize (1st page)

Display 20 items at a time ページネーション_1st.png

Screen you want to realize (2nd page)

Since there are 21 cases in total, only one case is on the second page. ページネーション_2nd.png

Pagination function implementation

Implementation part

Use kaminari to achieve pagination Add the following

Gemfile


gem 'kaminari'
gem 'kaminari-bootstrap'

Install gem below

console


bundle install

controller per (num): How many nums are displayed (every 20 this time) Changed with reference to the following differences

app/controllers/users_controller.rb


 def index
-  @users = User.all
+  @users = User.page(params[:page]).per(20)
 end

** View ** Pagination is displayed where you wrote paginate (this time it is behind the table)

diff:app/views/users/index.html.erb


 <div class="mt-2 mb-2 mr-5 ml-5 pr-5 pl-5">
   <table class="table table-sm table-hover">
     <thead class="thead-dark">
       <tr>
         <th>Name</th>
         <th>Email</th>
         <th></th>
         <th></th>
         <th></th>
       </tr>
     </thead>

     <tbody>
       <% @users.each do |user| %>
         <tr>
           <td><%= user.name %></td>
           <td><%= user.email %></td>
           <td><%= link_to 'Show', user %></td>
           <td><%= link_to 'Edit', edit_user_path(user) %></td>
           <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
         </tr>
       <% end %>
     </tbody>
   </table>
+  <%= paginate @users %>
 </div>
Screen (partially omitted)

ページネーション01.png

Pagination has been achieved, but it looks ugly and difficult to use.

Change in appearance

Create a file to customize kaminari below

console


rails g kaminari:views default

If you see the following, you have a kaminari folder in app/views

result


      create  app/views/kaminari/_paginator.html.erb
      create  app/views/kaminari/_prev_page.html.erb
      create  app/views/kaminari/_page.html.erb
      create  app/views/kaminari/_last_page.html.erb
      create  app/views/kaminari/_gap.html.erb
      create  app/views/kaminari/_first_page.html.erb
      create  app/views/kaminari/_next_page.html.erb

Edit the file generated in app/views/kaminari (mainly apply page-link class)

erb:app/views/kaminari/_first_page.html.erb


<span class="first">
  <%= link_to_unless current_page.first?, t('views.pagination.first').html_safe, url, :remote => remote, class: 'page-link' %>
</span>

erb:app/views/kaminari/_last_page.html.erb


<span class="last">
  <%= link_to_unless current_page.last?, t('views.pagination.last').html_safe, url, :remote => remote, class: 'page-link' %>
</span>

erb:app/views/kaminari/_next_page.html.erb


<span class="next">
  <%= link_to_unless current_page.last?, t('views.pagination.next').html_safe, url, :rel => 'next', :remote => remote, class: 'page-link' %>
</span>

erb:app/views/kaminari/_page.html.erb


<% if page.current? %>
  <span class="page-item disabled">
    <%= link_to page, url, {class: 'page-link'} %>
  </span>
<% else %>
  <span class="page-item">
    <%= link_to_unless page.current?, page, url, {:remote => remote, class: 'page-link', :rel => page.next? ? 'next' : page.prev? ? 'prev' : nil} %>
  </span>
<% end %>

erb:app/views/kaminari/_prev_page.html.erb


<span class="prev">
  <%= link_to_unless current_page.first?, t('views.pagination.previous').html_safe, url, :rel => 'prev', :remote => remote, class: 'page-link' %>
</span>

By the way, center the pagenation

app/assets/stylesheets/application.scss


.pagination {
  justify-content: center;
}

Screen (partially omitted)

ページネーションpage-link_中央寄せ.png

Pagination function completed Japanese localization methods such as Next and Last are omitted.

reference

[Rails] Create pagination using kaminari --Qiita [Rails] Let's master how to use kaminari! --Pikawaka Summary of how to use Kaminari --Hatena Blog

bonus

The following can be considered as additional requirements

――We decided to display 20 items per page, but we want to allow users to switch the number of items displayed. ――I want to know how many cases are displayed in total and how many of them are displayed in page nations.

Image (partially omitted)

完成イメージ.png

A function that allows the user to switch the number of displayed items

controller

app/controllers/users_controller.rb


 def index
-  @users = User.page(params[:page]).per(20)
+  @users = User.page(params[:page]).per(per_page)
 end

 ###Some parts are omitted below###

 private
+  def per_page
+    #This time 5, 10, 20, 50,Allow users to switch in 100 cases (default is 20)
+    %W[5 10 20 50 100].include?(params[:per]) ? params[:per] : 20
+  end

View

diff:app/views/users/index.html.erb


 <div class="mt-2 mb-2 mr-5 ml-5 pr-5 pl-5">
+  <div class="float-right">
+Displayed results:
+    <% [5, 10, 20, 50, 100].each do |per| %>
+      <% unless @users.limit_value == per %>
+        <%= link_to per, users_path(per: per), {class: 'mr-2'} %>
+      <% else %>
+        <a class="mr-2"><%= per %></a>
+      <% end %>
+    <% end %>
+  </div>
   <table class="table table-sm table-hover">
     <thead class="thead-dark">
       <tr>
         <th>Name</th>
         <th>Email</th>
         <th></th>
         <th></th>
         <th></th>
       </tr>
     </thead>
     <tbody>
       <% @users.each do |user| %>
 ###The following is omitted###
Display number switching screen (partially omitted)

This time I displayed it on the table Place as you like

表示件数切り替え機能.png

Total number and display number display

View

diff:app/views/users/index.html.erb


 <div class="mt-2 mb-2 mr-5 ml-5 pr-5 pl-5">
+  <div class="float-left">
+    <%= "#{@users.count}Case/ #{@users.total_count}Case" %>
+  </div>
   <div class="float-right">
Displayed results:
     <% [5, 10, 20, 50, 100].each do |per| %>
       <% unless @users.limit_value == per %>
         <%= link_to per, users_path(per: per), {class: 'mr-2'} %>
       <% else %>
         <a class="mr-2"><%= per %></a>
       <% end %>
     <% end %>
   </div>
 ###The following is omitted###
Total number and display number display screen

The number of items displayed per page is set to 20, but since the last page is only one item, it is displayed correctly (upper left).

全件と件数表示画面.png

Recommended Posts

[Rails] Add page nation to table [For beginners]
Migration file to add comment to Rails table
How to implement login request processing (Rails / for beginners)
(For beginners) [Rails] Install Devise
[Rails] Add column to devise
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
Tutorial to create a blog with Rails for beginners Part 2
Tutorial to create a blog with Rails for beginners Part 0
[Rails] How to display error messages for comment function (for beginners)
How to add columns to a table
[Rails] How to add new pages
[Rails] Add strong parameters to devise
[RSpec on Rails] How to write test code for beginners by beginners
[Rails] resources, member, collection Routing/named path/how to remember URL [for beginners]
[Rails] How to change the page title of the browser for each page
How to build a Ruby on Rails environment using Docker (for Docker beginners)
[Must-see for beginners] rails_12factor is not required to publish Rails app to Heroku
[Ruby on Rails] About bundler (for beginners)
Rails [For beginners] Implementation of comment function
(For beginners) [Rails] Time saving tech! How to install and use slim
[Ruby] How to use slice for beginners
[Rails] [Memo] When to add = to <%%> and when not
Explanation of Ruby on rails for beginners ①
[Rails] How to create a table, add a column, and change the column type
[For Rails beginners] Summary of how to use RSpec (get an overview)
[Rails] Articles for beginners to organize and understand the flow of form_with
[For beginners] How to debug in Eclipse
[For rails beginners] Specify transition destination after logging in to multiple Devise models
[Rails] Button to return to the top of the page
How to add / remove Ruby on Rails columns
Add a tag function to Rails. Use acts-as-taggable-on
[Rails] How to implement unit tests for models
[For beginners] How to implement the delete function
How to conditionally add html.erb class in Rails
[Rails] How to use Gem'rails-i18n' for Japanese support
Rails beginners tried to get started with RSpec
[For beginners] Procedure for creating a controller using rails
[For super beginners] How to use autofocus: true
[Introduction to Java] Basics of java arithmetic (for beginners)
Add binding.pry (rails)
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
[Rails] How to create a signed URL for CloudFront
[For beginners] Let's be able to coat like Swift!
Rails / Ruby: How to get HTML text for Mail
[Rails] Return login result in JSON format (for beginners)
How to make an almost static page with rails
[For beginners] How to operate Stream API after Java 8
[Spring Boot] How to create a project (for beginners)
[For Rails beginners] Implemented multiple search function without Gem
[Rails] How to change the column name of the table
[For beginners] Minimum sample to display RecyclerView in Java
Java development for beginners to start from 1-Vol.1-eclipse setup
Introduction to Java for beginners Basic knowledge of Java language ①
[Rails 6] Add images to seed files (using Active Storage)
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
Beginners use ubuntu in windows to prepare rails environment
How to use GitHub for super beginners (team development)
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~