Ask A Question

Notifications

You’re not receiving notifications from this thread.

Setting up “Next post” and “Previous post”

Lauro asked in General

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

Reply

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

Reply

👍🎉

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.