# Next/Previous record?

**URL:** <https://www.ruby-forum.com/t/next-previous-record/114672>\
**Category:** Rails\
**Created:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/next-previous-record/114672 "2007-09-17T13:24:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jables](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/58956e/32.png) [@Jables](https://www.ruby-forum.com/u/Jables)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/next-previous-record/114672/1 "2007-09-17T13:24:02Z")

</div>

Is there a way to get the next or previous record from a table or from  
a model?

Thanks,  
John

---

<div class="post-metadata">

**Author:** ![Jables](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/58956e/32.png) [@Jables](https://www.ruby-forum.com/u/Jables)\
**Post date:** [September 17, 2007, 1:25pm UTC](https://www.ruby-forum.com/t/next-previous-record/114672/2 "2007-09-17T13:25:00Z")

</div>

On Sep 16, 2007, at 10:50 PM, Jables wrote:

> Is there a way to get the next or previous record from a table or from  
> a model?
> 
> Thanks,  
> John

This is how I did it for one recent client:

def self.prior\_to id  
find(:first, :conditions =\> [“#{primary\_key} \< ?”, id], :order  
=\> “#{primary\_key} DESC”) ||  
find(:first, :conditions =\> [“#{primary\_key} \>= ?”,  
id], :order =\> “#{primary\_key}”)  
end

def self.next\_after id  
find(:first, :conditions =\> [“#{primary\_key} \> ?”, id], :order  
=\> “#{primary\_key}”) ||  
find(:first, :conditions =\> [“#{primary\_key} \<= ?”,  
id], :order =\> “#{primary\_key} DESC”)  
end

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid
