问题
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!
回答1:
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.
回答2:
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.
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/12291143/will-paginate-show-the-last-page-by-default-keeping-chronological-order