Scott Holland wrote:
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 = Paginator.new(self, @posts.length, posts_per_page,
@posts = @posts[offset..(offset + posts_per_page - 1)]
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?
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 = Paginator.new(self, 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'