bbonamin
bbonamin

Reputation: 30793

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!

Upvotes: 4

Views: 2694

Answers (4)

Mauricio Amorim
Mauricio Amorim

Reputation: 11

Try this code:

if params[:page]
    @collection = @q.result(distinct: true).paginate(:page => params[:page], :per_page => 30)
session[:lastpage] = params[:page]
else
    @collection = @q.result(distinct: true).paginate(:page => session[:lastpage] = params[:page], :per_page => 30)
end

Upvotes: 1

Fatou Kine Diop
Fatou Kine Diop

Reputation: 1

if params[:page]
    @collection = ordered_query_results.paginate(page: params[:page], per_page: PER_PAGE)
else
    total_results = ordered_query_results.count
    last_page = total_results / PER_PAGE + (total_results % PER_PAGE == 0 ? 0 : 1)
    @collection = ordered_query_results.paginate(page: last_page, per_page: PER_PAGE)
end

Upvotes: 0

bbonamin
bbonamin

Reputation: 30793

This is the solution I finally arrived to:

if params[:page]
    @collection = @q.result(distinct: true).paginate(:page => params[:page], :per_page => 30)
else
    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)
end

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.

Upvotes: 1

PinnyM
PinnyM

Reputation: 35531

You can build your query, get the total pages on the first pass, then fetch the last page on the next pass.

query = Log.some_scope
total_pages = query.paginate(:page => 1).total_pages
@logs = query.paginate(:page => total_pages)

You can also try the Kaminari gem instead of will_paginate which makes this a bit more comfortable.

Upvotes: 3

Related Questions