Rails

Next And Previous Links In Rails

Posted by Weston Ganger on March 18, 2015

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
  end

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

Then just call it like so:


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

Posted in Rails and Tagged with rails active-record 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts