Create pagination function with Rails Kaminari

version

・ Ruby 2.6.6 ・ Rails 5.2.4.1

Implemented gem'kaminari'

When creating an app with a posting function, the pagination function is also essential for UX. Therefore, we will implement the pagination function using Kaminari of gem.

First add kaminari to your Gemfile and run bundle install

Gemfile


gem 'kaminari', '~> 1.2.0'

Terminal


bundle install

Fix Controller

If you have already created a post feature and have a post list page, you need to modify the Controller. The Controller in the original post list page is as follows.

controllers/posts_controller.rb


def index
 @posts = Post.all
end

Change these as follows.

controllers/posts_controller.rb


def index
 @posts = Post.page(params[:page]).per(10)
end

With the addition of Kaminari, you can use the methods page and per on each model. Pass the current number of pages in the argument of the page method, and pass the number of pages to divide in the argument of per. Here, 10 is entered in the argument of per, but if you want to separate pages by 8 items, set the argument to 8.

View changes

When displaying the post list page, I think that it is common to use each statement, but it is used in ruby Add <% = pagenate @posts%> after <% end%>. When using haml, it seems good to write = paginate @posts at the end of list. For details, there are people who write articles using haml, so please refer to that.

ruby:views/posts/index.html.erb


 <% @posts.each do |post| %>
           .
           .
           .
 <% end %>
 <%= pagebate @posts %>

If there are no mistakes so far, the pagination link will be displayed automatically and the pagination function can be implemented. However, I don't think the design is easy to see. Therefore, use Bootstrap to arrange the design. If you have already installed Bootstrap, skip the next step.

Introducing Bootstrap

There are two ways to install Bootstrap, such as installing using yarn and downloading from the official Bootstrap website, but this time we will explain using the CDN method. If you are worried about the explanation here, https://www.youtube.com/watch?v=YY0mEyggH1E&t=713s There is a video that explains how to install it, so please have a look there.

There are two steps to take. The first is to write the code on the official website at the end of the head tag.

ruby:layouts/application.html.erb


<head>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>

The second is to write the code on the official website at the end of the body tag

ruby:layouts/application.html.erb


<body>

 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
 <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

</body>

This completes the installation.

Generate View template for Bootstrap 4

kaminari has themes that can be used in Bootstrap and foundation. If you execute the following code in the terminal, a View template for Bootstrap 4 will be generated under "app / views / kaminari". This View takes precedence over the kaminari default View.

Terminal


rails g kaminari:views bootstrap4

When completed so far, the design will look good. If that doesn't work, try restarting the server.

Also, if you don't like the English notation, you can use the Japanese notation. Add "config / locales / kaminari_ja.yml" and write as follows.

config/locales/kaminari_ja.yml


ja:
  views:
      pagination:
        first: 'the first'
        last: 'last'
        previous: 'Before'
        next: 'Next'
        truncate: '...'

If Japanese is not applied so far, add config.i18n.default_locale =: ja in "config / application.rb". Overall, it looks like this:

config/application.rb


require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Theclo
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
    config.i18n.default_locale = :ja
    config.time_zone = 'Tokyo'
  end
end

This completes the implementation. If that doesn't work, try restarting the server again. I hope it will be helpful to everyone.

Recommended Posts

Create pagination function with Rails Kaminari
[Rails 6] Pagination function implementation (kaminari)
Pagination function (kaminari)
Kaminari --Added pagination function of Rails
[Rails withdrawal] Create a simple withdrawal function with rails
Create an EC site with Rails 5 ⑩ ~ Create an order function ~
Login function implementation with rails
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
Create portfolio with rails + postgres sql
[Rails] Make pagination compatible with Ajax
Implemented mail sending function with rails
[Rails] Create an email sending function with ActionMailer (complete version)
Create My Page with Rails devise
[Rails] Create an evaluation function using raty.js
Create an infinite scroll with Infinite Scroll and kaminari
[Rails6] Create a new app with Rails [Beginner]
Create Rails 6 + MySQL environment with Docker compose
Make a login function with Rails anyway
[Rails 5] Create a new app with Rails [Beginner]
Create an or search function with Ransack.
[Rails 6] Ranking function
Implement Rails pagination
[Rails] Category function
Rails follow function
Create a SPA with authentication function with Rails API mode + devise_token_auth + Vue.js 3 (Rails edition)
[Rails] Notification function
Create authentication function in Rails application using devise
[Rails] rails new to create a database with PostgreSQL
How to create pagination for a "kaminari" array
Create a team chat with Rails Action Cable
Let's make a search function with Rails (ransack)
Create an EC site with Rails5 ⑤ ~ Customer model ~
Asynchronously output "html element of pagination" with kaminari
[Rails] Implementation of drag and drop function (with effect)
Rails deploy with Docker
[Rails 6] RuntimeError with $ rails s
[Rails] Implement search function
Create an EC site with Rails5 ④ ~ Header and footer ~
[Rails] Implemented hashtag function
Handle devise with Rails
[rails] tag ranking function
[Rails] Learning with Rails tutorial
Create an EC site with Rails5 ⑥ ~ seed data input ~
[Rails] Test with RSpec
Rails search function implementation
Implementation of pagination function
[Rails] Development with MySQL
Pagination implementation with gem'kaminari'
Supports multilingualization with Rails!
[Rails] Create initial data with seed.rb [Faker] [Japanese localization]
[Rails] Create an application
Double polymorphic with Rails
With Kotorin ―― 7. Scoping Function
Serverless Function with Micronaut
[For those who create portfolios] Search function created with ransack
Tutorial to create a blog with Rails for beginners Part 1
[Rails] I tried to create a mini app with FullCalendar
[Rails DM] Let's create a notification function when DM is sent!
[Rails] Create API to download files with Active Storage [S3]
A series of steps to create portfolio deliverables with Rails
[Ruby on Rails] Implement login function by add_token_to_users with API