Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: "Next post" and "Previous post" links in my show view, how to?

I'm new in Rails... smile

In my blog aplication I want to have a "Previous post" link and a "Next post" link in the bottom of my show view.

How do I do this?

Thanks!

like image 251
pollinoco Avatar asked Aug 14 '09 03:08

pollinoco


2 Answers

If each title is unique and you need alphabetical, try this in your Post model.

def previous_post
  self.class.first(:conditions => ["title < ?", title], :order => "title desc")
end

def next_post
  self.class.first(:conditions => ["title > ?", title], :order => "title asc")
end

You can then link to those in the view.

<%= link_to("Previous Post", @post.previous_post) if @post.previous_post %>
<%= link_to("Next Post", @post.next_post) if @post.next_post %>

Untested, but it should get you close. You can change title to any unique attribute (created_at, id, etc.) if you need a different sort order.

like image 192
ryanb Avatar answered Oct 17 '22 02:10

ryanb


I used the model methods as below to avoid the issue where id + 1 doesn't exist but id + 2 does.

def previous
  Post.where(["id < ?", id]).last
end

def next
  Post.where(["id > ?", id]).first
end

In my view code, I just do this:

<% if @post.previous %>
  <%= link_to "< Previous", @post.previous %>

<% if @post.next %>
  <%= link_to "Next >", @post.next %>
like image 15
Kevin Trotter Avatar answered Oct 17 '22 03:10

Kevin Trotter