Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOWTO rank items by balance in Ruby on rails

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.

like image 673
fenec Avatar asked May 11 '10 18:05

fenec


3 Answers

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.

like image 71
ejoubaud Avatar answered Oct 20 '22 23:10

ejoubaud


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

like image 20
Drew Johnson Avatar answered Oct 20 '22 23:10

Drew Johnson


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.

like image 5
fl00r Avatar answered Oct 21 '22 00:10

fl00r