Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Setting up “Next post” and “Previous post”

General • Asked by Lauro

In my blog application I want to have a "Previous post" link and a "Next post" link in the bottom of my show view. But I'm having a hard time getting it to work. What am I missing?

This is what I currently have:

Post Controllers

def next
    Post.where("id > ?", id).order(id: :asc).limit(1).first
end

def prev
     Post.where("id < ?", id).order(id: :desc).limit(1).first
end

Post Show

<%= link_to "Prev Post", @post.prev %>
<%= link_to "Next Post", @post.next %>

I had to add those variable into the Post Models and not the Post Controllers.

def next
    Post.where("id > ?", id).order(id: :asc).limit(1).first
end

def prev
     Post.where("id < ?", id).order(id: :desc).limit(1).first
end


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.