Next And Previous Links In Rails

Posted by Weston Ganger

Sometime you want to add Next or Previous links to your blog posts or whatever model. Its really easy, just add a couple of instance methods to your model

class Post < ActiveRecord::Base
  def next
    Post.where("id > ?", id).limit(1).first

  def prev
    Post.where("id < ?", id).limit(1).first

Then just call it like so:

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

Article Topic:Software Development - Rails

Date:March 18, 2015

Recommended Posts



Send Me A Message

I would love to get in touch and talk about your next project. Feel free to send a message and I will get back to you shortly.

Get Connected