I was in a similar situation, and in the end I got a couple of solutions using Rails 3.1.3 using methods or areas of the class (named_scope in Rails 2.x). This approach will work even with non-sequential identifiers.
An example of class methods using the Post model:
def next Post.where("posts.id > ?", self.id).order("posts.id ASC").limit(1) end def previous Post.where("posts.id < ?", self.id).order("posts.id DESC").limit(1) end
This can be used as:
post = Post.find(5) next_post = post.next => [
And for lambda applications, there should be something like:
scope :next, lambda { |i| {:conditions => ["#{self.table_name}.id > ?", i.id], :order => "#{self.table_name}.id ASC", :limit => 1} } scope :previous, lambda { |i| {:conditions => ["#{self.table_name}.id < ?", i.id], :order => "#{self.table_name}.id DESC", :limit => 1} }
source share