[Rilas] What I learned in implementing the pagination function.

I keep a memorandum of what I learned when I added the pagination function to the list display screen.

Premise

This is the view before the pagination function is added.

controller

A sort function is added in advance.

app/controller/stocks_controller.rb


class StocksController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
    @calendar = Calendar.find(params[:calendar_id])
    @stocks = @calendar.stocks.order("#{sort_column} #{sort_direction}")
    @products = Product.all
  end

  private

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc'
  end

  def sort_column
    Stock.column_names.include?(params[:sort]) ? params[:sort] : 'id'
  end

end

Helper method (additional note)

I omitted the description of the important helper method ...

app/helper/stocks_helper.rb


module StocksHelper
  def sort_order(column, title)
    css_class = (column == sort_column) ? "current #{sort_direction}" : nil
    direction = (column == sort_column && sort_direction == 'asc') ? 'desc' : 'asc'
    link_to title, { sort: column, direction: direction }, class: "sort_header #{css_class}"
  end
end

View

reb:app/views/stocks/index.html.erb


    <table>
      <thead>
        <tr>
          <th scope="col"><%= sort_order "display", "display" %></th>
          <th scope="col"><%= sort_order "publisher", "Publisher name" %></th>
          <th scope="col"><%= sort_order "magazine_name", "Journal title" %></th>
          <th scope="col"><%= sort_order "num", "Number of books" %></th>
          <th scope="col"><%= sort_order "price", "Base price" %></th>
          <th scope="col"><%= sort_order "i_form", "Issuance form" %></th>
          <th scope="col"><%= sort_order "purchased", "Purchased magazine" %></th>
        </tr>
      </thead>
      <tbody>
        <% @stocks.each do |stock| %>
          <% if stock.num > 0 %>
                <tr>
                  <td><%= stock.display %></td>
                  <td><%= stock.publisher %></td>
                  <td><%= stock.magazine_name %></td>
                  <td><%= stock.num %></td>
                  <td><%= stock.price.to_s(:delimited) %></td>
                  <td><%= stock.i_form %></td>
                  <td><%= stock.purchased %></td>
                </tr>
          <% end %>
        <% end %>
      </tbody>
    </table>

Implementation of pagenation

This time, I implemented it using a gem for page nation called kaminari. It was surprisingly easy to implement.

installation of kaminari

Add gem'kaminari' to your Gemfile and install it with $ bundle install.

Gemfile


gem 'kaminari'

After installing gem, restart the server once. You can stop the server with Ctrl-c and start the server with rails s. Also, I forgot and went back and forth ...

This completes the kaminari installation.

Display pagenation

Next is the controller. Add .page (params [: page]) to the data for which you want to display pagenations.

app/controllers/stocks_controller.rb


def index
  #For data you want to page.page(params[:page])Add
  @stocks = @calendar.stocks.page(params[:page]).order("#{sort_column} #{sort_direction}")
end

Digression (1. Change the number of records displayed on the page)

It seems that the number of records displayed on one page is 25 by default. It seems that you can change it by adding .per (number of records you want to display) to the controller.

For example, if you want to display 30 items, add .per (30).

app/controllers/stocks_controller.rb


def index
  # .per(30)Add
  @stocks = @calendar.stocks.page(params[:page]).per(30).order("#{sort_column} #{sort_direction}")
end

I feel like.

Finally, to the place where you want to display pagenation in view Add <% = paginate @stocks%>.

reb:app/views/stocks/index.html.erb


    <%= paginate @stocks %>
    <table>
~ ~ Omitted ~ ~
    </table>

Digression (2. Change the display to Japanese)

I found it difficult to understand the << First and <Prve before and after the page number. I will change this to Japanese.

config/application.rb


#~~abridgement~~
module Teiki29770(The app name)
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    #Japanese language setting
    config.i18n.default_locale = :ja
    config.time_zone = 'Tokyo'

    # 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.
  end
end

Let's restart the server! Create a yml file ja.yml for Japanese conversion in config/locales, Let's add the following code.

config/locales/ja.yml


ja:
  views:
    pagination:
      first: "&laquo;the first"
      last: "last&raquo;"
      previous: "&lsaquo;Before"
      next: "Next&rsaquo;"
      truncate: "..."

Now you can change the display to Japanese! !! I thought ...

There is a gap in the number of displays.

スクリーンショット 2020-12-16 16.17.28.png Something is few ... I should be able to display 30 items ... When I looked it up, the number of displays on other pages was different.

Caused by a conditional expression in the view

Send 30 data at a time as specified by the controller The cause was that the view was displaying only the data that matched the conditional expression.

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


~ ~ Omitted ~ ~
      <tbody>
        <% @stocks.each do |stock| %>
          <% if stock.num > 0 %>⇦ This is the cause.
                <tr>
                  <td><%= stock.display %></td>
                  <td><%= stock.publisher %></td>
                  <td><%= stock.magazine_name %></td>
                  <td><%= stock.num %></td>
                  <td><%= stock.price.to_s(:delimited) %></td>
                  <td><%= stock.i_form %></td>
                  <td><%= stock.purchased %></td>
                </tr>
          <% end %>
        <% end %>
      </tbody>
    </table>

Therefore, the controller first extracts only the data that meets the conditions. I will send 30 of them to the view.

app/controller/stocks_controller.rb



  def index
    @calendar = Calendar.find(params[:calendar_id])
    @stocks = @calendar.stocks.where("num > ?",0).page(params[:page]).per(30).order("#{sort_column} #{sort_direction}")

  end

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


~ ~ Omitted ~ ~
      <tbody>
        <% @stocks.each do |stock| %>
~ ~ Delete the if statement ~ ~
                <tr>
                  <td><%= stock.display %></td>
                  <td><%= stock.publisher %></td>
                  <td><%= stock.magazine_name %></td>
                  <td><%= stock.num %></td>
                  <td><%= stock.price.to_s(:delimited) %></td>
                  <td><%= stock.i_form %></td>
                  <td><%= stock.purchased %></td>
                </tr>
        <% end %>
      </tbody>
    </table>

With this, we were able to display the data according to the conditions firmly! スクリーンショット 2020-12-16 18.33.41.png You can also sort properly!

What I learned

I was able to reconfirm the importance of MVC relationships and the importance of firmly dividing roles. Thank you, Page Nation!

The site that I used as a reference

https://qiita.com/rio_threehouse/items/313824b90a31268b0074 Thank you!

Recommended Posts

[Rilas] What I learned in implementing the pagination function.
What I learned through the swift teacher
What i learned
What I learned in Java (Part 2) What are variables?
Summary of what I learned in Spring Batch
What I learned ② ~ Mock ~
What I learned ① ~ DJUnit ~
What I learned in Java (Part 3) Instruction execution statement
What I learned when building a server in Java
What I stumbled upon in the ActiveModel :: Serializer test
What I learned about Kotlin
What I did in the version upgrade from Ruby 2.5.2 to 2.7.1
What if I write a finally clause in the try-with-resources syntax?
What I have learned in Java (Part 1) Java development flow and overview
[Note] What I learned in half a year from inexperienced (Java) (1)
What I did in the migration from Spring Boot 1.4 series to 2.0 series
What is @Override or @SuppressWarnings ("SleepWhileInLoop") in front of the function? ?? ??
[Note] What I learned in half a year from inexperienced (Java) (3)
What I learned with Java Gold
What I did in the migration from Spring Boot 1.5 series to 2.0 series
I summarized the flow until implementing simple_calendar in Ruby on Rails.
What I learned with Java Silver
What are the rules in JUnit?
What I did when JSF couldn't display database information in the view
What I investigated in Wagby development Note 1
I tried the new era in Java
Rails refactoring story learned in the field
What is the main method in Java?
I tried the AutoValue library in Intellij
What I got into @Transactional in Spring
What I learned from Java monetary calculation
What is Pullback doing in The Composable Architecture
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
Summary of what I learned about Spring Boot
I tried to organize the session in Rails
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
Story of implementing update function in form object
[Swift] Various things I learned by implementing Realm
I want to get the value in Ruby