MVC and Pagination


#1

Just wondering how to best integrate with pagination and still stick to
MVC…

Say I have a Post model that has a published attribute. I want to show
all the recent published posts on a page.

My first instinct is to create a method in the Post model called recent
that does the find with proper conditions and order, but the problem I
have is how do I use that with pagination (which definitely does not
belong in model)?

Any ideas?

Thanks,

Chris


#2

Try scaffolding and base your own code on that source.
-Nathan


#3

Umm, scaffolding doesn’t really apply to what I am trying to do below.

Chris


#4

On 8-Jun-06, at 10:52 AM, Chris B. wrote:

that does the find with proper conditions and order, but the problem I
have is how do I use that with pagination (which definitely does not
belong in model)?

Any ideas?

Is there something wrong with doing something like this in your
controller?

@post_pages, @posts = paginate(Post,
:conditions => [‘published > ?’, 1.day.ago],
:order => “published DESC”,
:parameter => ‘page’,
:per_page => (params[:per_page] || 10).to_i
)

If you’re wanting to fully encapsulate the idea of ‘recent’ in your
model then go ahead and have a Post.recent method. You’ll also need
a Post.count_recent so that in your controller you can set up
pagination ‘classic’ style (but you’re kind of fighting the
framework). For example:

in post.rb:

def self.recent(limit = nil, offset = nil)
self.find(:all,
:conditions => [‘published > ?’, 1.day.ago],
:order => “published DESC”,
:limit => limit,
:offset => offset
)
end

def self.count_recent
self.count(conditions => [‘published > ?’, 1.day.ago])
end

and in your controller:

@post_pages = Paginator.new(self,
Post.count_recent(),
10, params[:page])
@post = Post.recent(@post_pages.items_per_page,
@post_pages.current.offset)

WARNING - this is off the top of my head, syntax errors might be in
there :slight_smile:

Either way should work, though just putting it all in the controller
(first example) is often clearer.

Regards,
Tervor

Trevor S.
http://somethinglearned.com