Posted By

gmericksen on 01/14/11


Tagged

rails


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jwilcox09


Previous and Next Links


 / Published in: Rails
 

URL: http://stackoverflow.com/questions/1275963/rails-next-post-and-previous-post-links-in-my-show-view-how-to

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.

  1. def previous_post
  2. self.class.first(:conditions => ["title < ?", title], :order => "title desc")
  3. end
  4.  
  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.
  9.  
  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  

You need to login to post a comment.