DEV Community

Cover image for Ruby on Rails Pagination
Ian Kamau
Ian Kamau

Posted on

Ruby on Rails Pagination

Hey Rubyist!

I'm excited to share with you a streamlined approach to implementing pagination in your Ruby on Rails blog application. Pagination can be a bit tricky, but fear not! The Ruby community has gifted us with a gem that simplifies the process.

Let's get started:

Create a new Ruby on Rails application:

   rails new <name_of_your_project>
   cd <name_of_your_project>
Enter fullscreen mode Exit fullscreen mode

Generate a scaffold for your blog posts:

rails generate scaffold Post title:string content:text
Enter fullscreen mode Exit fullscreen mode

Using a scaffold is convenient as it creates everything from controllers to views to models, saving you time.

Perform migrations:

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

This ensures your database is set up with the new Post model.

Open application_controller.rb and include the following code:

include Pagy::Backend
Enter fullscreen mode Exit fullscreen mode

In application_helper.rb, add:

include Pagy::Frontend
Enter fullscreen mode Exit fullscreen mode

Create a file named pagy.rb in the config/initializers folder, and insert:

Pagy::DEFAULT[:items] = 5
Enter fullscreen mode Exit fullscreen mode

Here, we specify that we want 5 items/posts per page.

Update the index method in posts_controller.rb:

def index
  @pagy, @posts = pagy(Post.order(created_at: :desc))
end
Enter fullscreen mode Exit fullscreen mode

This code fetches a paginated list of posts ordered by creation date in descending order, storing pagination information (@pagy) and the posts (@posts) in instance variables.

In views/posts/index.html.erb, add:

<div>
    <% @posts.each do |post| %>
        <h2>
            <%= link_to post.title, post %>
        </h2>
    <% end %>

    <div>
        <%== pagy_nav(@pagy) if @pagy.pages > 1 %>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

This template iterates through the collection of posts, displaying each post's title as a link. If pagination is necessary (more than one page), it displays the pagination navigation at the bottom.

Now you have a robust pagination setup for your Ruby on Rails blog application! Remember to test thoroughly, consider alternative gems like kaminari if needed, and keep an eye on gem updates for any improvements or changes.

Top comments (2)

Collapse
 
pimp_my_ruby profile image
Pimp My Ruby

Hiii ! Nice article :)

Why did you use Pagy ?

Collapse
 
iankcode profile image
Ian Kamau

Hello! Thank you! 😊 I chose Pagy for its simplicity and efficiency in handling pagination. It offers a lightweight solution with easy integration, contributing to a smoother user experience.