Pagy, Load more with turbo rails 7

08 Jun 2022
1:36 min read

This blog, I am going to show you how to do loadmore with pagy gem in ‘rails way’

For pagy gem you can find an installation guideline in Pagy Githug

You just have to add next page turbo frame in the current turbo frame to make to make it work.

Here is the example

main file html.erb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
      <%= render partial: 'posts/post_comments/comment',
                 locals: { comment: @top_comment, is_top_comment: true } if @top_comment.present? %>
      <%= turbo_frame_tag "post-comments-#{@pagy.page}" do %>

        <% comments.each do |comment| %>
          <%= render partial: 'posts/post_comments/comment',
             locals: {comment: comment, is_top_comment: false} %>
        <% end %>

        <%= turbo_frame_tag "post-comments-#{@pagy.next}" do %>
          <%= render partial: 'application/load_more',
                     locals: {
                       pagy: @pagy
                     } %>
        <% end %>
      <% end %>

application/_load_more.html.erb

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="text-center mt-4">
  <% if pagy.next.present? %>
    <div class="mt-3">
      <%= link_to 'Load More',
                  pagy_url_for(pagy, pagy.next) %>
    </div>
  <% end %>
  <% if pagy.count > 0 %>
    <div class="mt-3">
      <%= "#{pagy.to} / #{pagy.count}" %>
    </div>
  <% end %>
</div>
Tawin Supayanant
Developer who optimises business value by putting in a reasonable effort