Previous and Next Links

/ Published in: Rails
Save to your folder(s)

If each title is unique and you need alphabetical, try this in your Post model. You can change title to any unique attribute (created_at, id, etc.) if you need a different sort order.

Copy this code and paste it in your HTML
  1. def previous_post
  2. self.class.first(:conditions => ["title < ?", title], :order => "title desc")
  3. end
  5. def next_post
  6. self.class.first(:conditions => ["title > ?", title], :order => "title asc")
  7. end
  8. You can then link to those in the view.
  10. <%= link_to("Previous Post", @post.previous_post) if @post.previous_post %>
  11. <%= link_to("Next Post", @post.next_post) if @post.next_post %>


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.