10

I am implementing a betting system and each user has a balance , how can i find a rank of a user using activerecord methods? thanks for your help.

1

4 Answers 4

20

To get the rank of a user,

Users.all(:order => "balance").index(a_particular_user)

This should give you the index (rank) of a particular user within the array of all users (sorted by balance).

0
10

A slightly more efficient solution if you have a lot of users:

Users.order(:balance).pluck(:id).index(a_particular_user_id)`

That way, your app fetches n integer ids instead of pulling and instantiating n whole User records/objects. Could end up orders of magnitude faster.

1
  • 1
    With this method my query took 30 ms, using only ".index" through the user object, took 250ms. Very efficient solution! Feb 26, 2015 at 16:54
5

few days ago I've asked just the same question

Position of object in database

my solution was just the same as @Drew Johnson suggested (User.all.index current_user). But I needed "query solution" and @Vlad Zloteanu gave me great idea:

User.count(:order => "balance", :conditions => ['balance < (?)', current_user.balance])

this is fast query solution for big tables of data.

3

If I understood what you want, you just need to order the users by balance

User.all(:order => "balance")

Edit: unless balance isn't an attribute...

Edit#2: after seeing Drew Johnson's answer I realized I misunderstood your question. As he said, you can use the index method to do what you want.

@user = User.first
@rank = User.all(:order => "balance").index(@user)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.