views:

70

answers:

3

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.

+3  A: 

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)
j.
thank you , my problem is fixed
fenec
+3  A: 

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).

Drew Johnson
thank you , my problem is fixed
fenec
+2  A: 

few days ago I've asked just the same question

http://stackoverflow.com/questions/2763801/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.

fl00r