Forum: Ruby on Rails Redirect to last page in pagination

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
60071e44382435f0f42bf6c3f6e29889?d=identicon&s=25 Scott Holland (ginsberg1982)
on 2007-01-06 23:01

I have a forum and at the bottom of each page of the current topic I
have a form to add a reply.

I am using the following pagination to display 20 posts per topic per

      page = (params[:page] ||= 1).to_i
      posts_per_page = 20
      offset = (page - 1) * posts_per_page

      @posts = Post.find(:all, :conditions => ["topic_id = ?",
params[:id]], :order => "created_on DESC")

      @post_pages =, @posts.length, posts_per_page,

      @posts = @posts[offset..(offset + posts_per_page - 1)]

My question is:

When a user adds a reply, I want to then redirect that person to the
last page of posts (which is where their reply will have been added)

Any ideas how i could go about this?

B0f09f622c913a13b9bfd332fca56563?d=identicon&s=25 Dan Manges (Guest)
on 2007-01-07 20:11
(Received via mailing list)
Scott Holland wrote:
> last page of posts (which is where their reply will have been added)
> Any ideas how i could go about this?

Pagination is a highly debated topic with several ways of implementing
it.  While it may be better to use one of the pagination plugins, here
is a suggestion based on your current implementation.

To get the number of total posts, use: Posts.count  - your current code
selects every single post from the database on a request to that
action, which is inefficient and will not scale.

You could support a custom ?page=last parameter.

total = Post.count
limit = 20
page = params[:page] || 1
page = (total.to_f / limit).ceil if page == "last"

@posts = Topic.find(params[:id]).posts.find(all, :limit => limit,
:offset => (page.to_i-1)*limit, :order => "created_on DESC")
@post_pages =, total, limit, page.to_i)

I'm not sure this is the cleanest way to implement what you want, but
it will work.

redirect_to :controller => 'posts', :action => 'list', :page => 'last'

Dan Manges
60071e44382435f0f42bf6c3f6e29889?d=identicon&s=25 Scott Holland (ginsberg1982)
on 2007-01-09 12:48

Thanks for that. I'll give it a go.

I never actually thought about pagination plugins. Are there any you
would recommended?

3d1a70ebd35ac970e009e01599603b46?d=identicon&s=25 koloa (Guest)
on 2007-01-09 14:47
question about pagination and how it does not scale well, what size
recordset will pagination start being a problem? < 1000, > 2000, a few
hundred? or are we talking 10k and above?
This topic is locked and can not be replied to.