JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
April 26, 2011

Reverse Pagination Count with Kaminari

When displaying a threaded conversation with messages paginated by Kaminari, I had the unique requirement to display messages in DESC order by their creation date. This meant that if there were 12 messages with 5 per page, the breakdown would be

  • Page 1: messages 12 - 8
  • Page 2: messages 7 - 3
  • Page 3: messages 2 - 1

To actually display the message number next to each message, it had to be calculated using the methods added to a paginated model by Kaminari (see the :message_number value below)

<div class="comments">
  <% @messages.each_with_index do |message, index| %>
    <%= render :partial => 'message', :locals => {:message => message, :message_number => @messages.total_count - (@messages.current_page - 1) * @messages.limit_value - index} %>
  <% end %>
</div>

For now this is the only place the above calculation is relevant. Should I need it in multiple places I would move the above calculation to a helper.

3 notes Tags: rails ruby on rails RoR code tips ruby kaminari

  1. d4ly posted this