All threads / Setting up “Next post” and “Previous post”

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

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

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.