Forum: Ruby on Rails MVC and Pagination

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris B. (Guest)
on 2006-06-08 21:55
(Received via mailing list)
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
unknown (Guest)
on 2006-06-08 22:14
(Received via mailing list)
Try scaffolding and base your own code on that source.
-Nathan
Chris B. (Guest)
on 2006-06-08 23:23
(Received via mailing list)
Umm, scaffolding doesn't really apply to what I am trying to do below.



Chris
Trevor S. (Guest)
on 2006-06-08 23:51
(Received via mailing list)
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 :-)

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

Regards,
Tervor
--
Trevor S.
http://somethinglearned.com
This topic is locked and can not be replied to.