bruno077 bruno077 - 1 year ago 60
Ruby Question

will_paginate show the last page by default (keeping chronological order)

I'm building an index page where I need to display results which have a date, ordered chronologically (from the earliest date to the newest one), but I need to always show the last page by default.

I can't use a DESC order for the date because it would defeat the whole purpose of what I need this for =(.

TL;DR: I need to show a paginated log list, sorted by date ascending, but starting in the last page. Is this possible with will_paginate? Thanks!

Answer Source

This is the solution I finally arrived to:

if params[:page]
    @collection = @q.result(distinct: true).paginate(:page => params[:page], :per_page => 30)
    last_page = @q.result(distinct: true).paginate(:page => params[:page], :per_page => 30).total_pages
    @collection = @q.result(distinct: true).paginate(:page => last_page, :per_page => 30)

It's not fancy, it needs some refactoring and perhaps can use memoization to avoid calling the paginate method twice, but hey it works. If you are trying to access a page directly, it is rendered as usual, but if you don't specify a page, you are taken to the last page by default.