Jacek Podkanski wrote:
> I have a Persons table created with scaffold. I was trying to flick
> between records by clicking on Previous and Next links. I was
> struggling to understand will_paginate, and finally came up with
> following solution, and I'm wondering if it could be done better.
> Would it be better to have one query to a database returning previous
> current and next record instead having two?
> 
> @person_previous = Person.paginate :all, :page => params[:page],
>   :order => 'id DESC', :per_page => 1, :conditions => "id <
> #{params[:id]}"
> @person_next = Person.paginate :all, :page => params[:page],
>   :order => 'id ASC', :per_page => 1, :conditions => "id >
> #{params[:id]}"
> 
> <% @person_previous.each do |el|%>
> <%= link_to 'Previous', el %>
> <% end %>
> 
> <% @person_next.each do |el|%>
> <%= link_to 'Next', el %>
> <% end %>

First, yeah, never directly interpolate query parameters (or any user 
input) into your SQL queries. Second, use the paginate method to only 
fetch the records relevant for the current page, as the will_paginate 
view helper takes care of the rest. Did you look at the documentation 
(http://gitrdoc.com/mislav/will_paginate/tree/master/) for the 
will_paginate method? It's designed to generate the Previous, Next, and 
anything-in-between links for you...

ESSENTIALLY, you just wanna do this in your controller:

@people = Person.paginate, :per_page => 1, :page => params[:page], 
:order => "id ASC"

and then in your view just

<%= will_paginate @people, :page_links => false %>


The gem does pretty much everything for you, just take the time to 
understand the documentation and the examples, and read the source for 
anything that's still doesn't make sense.
-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to