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
  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 %>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.