Skip to content

Backend Training: Pagination

Nelson Lee edited this page Nov 30, 2017 · 1 revision

🔖 : will_paginate, will_paginate_bootstrap

Create a controller

$ rails g controller posts

Add the actions to post controller

class PostsController < ApplicationController

  def index
    @posts = Post.published.by_published_date
  end

  def show
    @post = Post.published.friendly.find params[:id]
  end

end

Add routes

# app/config/routes.rb
Rails.application.routes.draw do
  .....

  resources :faqs,  only: %i[index]
  resources :posts, only: %i[index show]

  .....
end

Add views

Create a template for index action

# app/views/posts/index.slim
section.jumbotron[id='hero']
  .container
    .row.text-center
      .col-md-12
        h1= t('.title')

section[id='posts']
  .container
    .row
      .col-md-8
        .row
          = render @posts
      .col-md-4

Create a partial for aside

# app/views/posts/_aside.slim
aside
  .panel.panel-default
    .panel-heading.text-uppercase
      = t('.archives.title')
    .panel-body

Add aside to the index page

# app/views/posts/index.slim
section.jumbotron[id='hero']
  .....

section[id='posts']
  .container
    .row
      .col-md-8
        .row
          = render @posts
      .col-md-4
        = render 'aside'

Add links to the navbar

# app/views/components/_navbar.slim
nav.navbar.navbar-default
  .container
    .navbar-header
      ......
    .collapse.navbar-collapse[id='main-nav']
      ul.nav.navbar-nav.navbar-right
        ......
        li= link_to t('.posts'), posts_path

Add Translations

en:
  activerecord:
    .....

  components:
    navbar:
      ......
      posts: NEWS
    footer:
      copyright: '%{year} © Clever Banana Studios Inc. All Rights Reserved.'

  home:
    .....

  faqs:
    .....

  posts:
    index:
      title: News

Refresh the browser Command ⌘+r, and click on the post link you should be able to go to /posts and see the list of posts. post#index

Add Pagination

Next, let's add pagination to posts. We can do this by using the will_paginate gem(doc)

Change controller to

# app/controllers/posts_controller.rb
class PostsController < ApplicationController

  def index
    @posts = Post.published.by_published_date.
             paginate(page: params[:page], per_page: 9)
  end

  ......

end

Change views to

# app/views/posts/index.slim
section.jumbotron[id='hero']
  .....

section[id='posts']
  .container
    .row
      .col-md-8
        .row
          = render @posts
        .row
          .col-md-12
            .text-center
              = will_paginate @posts, renderer: BootstrapPagination::Rails,\
                inner_window: 1, outer_window: 1
      .col-md-4
        = render 'aside'

We use will_paginate-bootstrap gem(doc) here to make the pagination work with bootstrap components. Refresh the browser Command ⌘+r, and you should see the pagination at the bottom of the page.

post#index_pagination

↪️ Next Section: Filter

Clone this wiki locally