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>
Generate a scaffold for your blog posts:
rails generate scaffold Post title:string content:text
Using a scaffold is convenient as it creates everything from controllers to views to models, saving you time.
Perform migrations:
rails db:migrate
This ensures your database is set up with the new Post model.
Open application_controller.rb and include the following code:
include Pagy::Backend
In application_helper.rb, add:
include Pagy::Frontend
Create a file named pagy.rb in the config/initializers folder, and insert:
Pagy::DEFAULT[:items] = 5
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
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>
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)
Hiii ! Nice article :)
Why did you use Pagy ?
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.