# Getting the position of a record within an index

**URL:** <https://www.ruby-forum.com/t/getting-the-position-of-a-record-within-an-index/115722>\
**Category:** Rails\
**Created:** [September 27, 2007, 10:37pm UTC](https://www.ruby-forum.com/t/getting-the-position-of-a-record-within-an-index/115722 "2007-09-27T22:37:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ben\_Nevile](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/48db29/32.png) [@Ben\_Nevile](https://www.ruby-forum.com/u/Ben_Nevile)\
**Post date:** [September 27, 2007, 10:37pm UTC](https://www.ruby-forum.com/t/getting-the-position-of-a-record-within-an-index/115722/1 "2007-09-27T22:37:19Z")

</div>

Hi,

Let’s say that in my “users” table I have a column called “points”  
that is indexed. I would like to be able to query the position of any  
given user within that index. In other words, I want the same data  
that the following method would give:

def rank  
result = 0  
User.find(:all).each {|u| result=result+1 if u.points \> points}  
result  
end

However I can’t use the above method because the user database has a  
quarter of a million records and is growing.

Help! and Thanks in advance.  
Ben

---

<div class="post-metadata">

**Author:** ![Ben\_Nevile](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/48db29/32.png) [@Ben\_Nevile](https://www.ruby-forum.com/u/Ben_Nevile)\
**Post date:** [September 28, 2007, 12:47am UTC](https://www.ruby-forum.com/t/getting-the-position-of-a-record-within-an-index/115722/2 "2007-09-28T00:47:36Z")

</div>

On Sep 27, 2007, at 3:42 PM, Ben Nevile wrote:

> result  
> end
> 
> However I can’t use the above method because the user database has a  
> quarter of a million records and is growing.
> 
> Help! and Thanks in advance.  
> Ben

class User  
def self.having\_more\_points\_than points  
count(:conditions =\> [‘points \> ?’, points])  
end

def rank  
self.class.having\_more\_points\_than(self.points) + 1  
end  
end

You might want to save the value in an instance variable if you refer  
to the rank more than once per request.

-Rob

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

---

<div class="post-metadata">

**Author:** ![Ben\_Nevile](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/48db29/32.png) [@Ben\_Nevile](https://www.ruby-forum.com/u/Ben_Nevile)\
**Post date:** [September 28, 2007, 2:37am UTC](https://www.ruby-forum.com/t/getting-the-position-of-a-record-within-an-index/115722/3 "2007-09-28T02:37:21Z")

</div>

ah, that is great Rob – thanks!!

Ben
