views:

792

answers:

3

I am new to rails so go easy. I have built my first blog and would like to set it up such that in the <% post.each do |post| %> render of the posts, I would like it to work such that it only displays 10 posts and then has a link to view the next 10.

I am hoping this is an easy question. Let me know if you would like me to post any code.

+5  A: 

You should use the gem will_paginate.

The installation and usage is really easy: http://wiki.github.com/mislav/will%5Fpaginate/installation

Example usage: http://github.com/mislav/will%5Fpaginate

brainfck
+2  A: 

Check out the will_paginate Gem.

It’s very easy to do pagination on ActiveRecord models:

@posts = Post.paginate :page => params[:page], :order => 'created_at DESC'

In the view, page links can be rendered with a single view helper:

<%= will_paginate @posts %>
Simone Carletti
Since I am new I will ask a stupid question. Do I put the first line of code in the Model or the controller. I thought model based on your answer but didn't work. Here is what I typed:def will_paginate @posts = Post.paginate :page => params[:page], :order => 'created_at DESC'end
bgadoci
No formatting in comments but you get it.
bgadoci
The code is intended to be placed in the controller. If you want, you can also use the #paginate method in your model to create a custom method.
Simone Carletti
Ok, thanks. Just having trouble installing plugin from errtheblog.com
bgadoci
It's easiest to install the plugin as a gem, via RubyGems.
mlambie
$ gem install will_paginate
mlambie
+1  A: 

will_paginate is definitely the way to go, I just thought I'd add a link to a railscasts will_paginate video showing you how to use it since sometimes that can be an easier way to learn the basics than reading documentation. Plus you'll learn a brief history on how pagination used to be done when it was an included part of Rails (it was slower and more cumbersome). The old classic pagination has been moved out into it's own plugin too, but it's only recommended if you were already using it when you upgraded Rails to a version where they took it out.

Railscasts has a ton of other great videos that you might find helpful. For example, once you get more advanced you might want to try ajax pagination

mmrobins
This is awesome, thanks.
bgadoci