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.
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.
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).
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With