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.
4 Answers
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).
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.
-
1With 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
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.
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)