def best_drivers(limit = 10)
lost = 'SELECT COUNT(c.id) FROM challenges AS c
WHERE (c.challenger_id = u.id AND c.challenge_state_id = 5)
OR (c.opponent_id = u.id AND c.challenge_state_id = 4)'
won = 'SELECT COUNT(c.id) FROM challenges AS c
WHERE (c.challenger_id = u.id AND c.challenge_state_id = 4)
OR (c.opponent_id = u.id AND c.challenge_state_id = 5)'
# WHERE statement prevents division by zero
find_by_sql(
'SELECT u.*, cast(('+won+') as float)/(cast(('+won+') as float)+cast(('+lost+') as float)) AS win_ratio, ('+won+') AS won, ('+lost+') AS lost
FROM users AS u
WHERE ('+won+') > 0
ORDER BY win_ratio DESC, won DESC
LIMIT '+limit.to_s
)
end
I’m using this query to sort the users in the ranking table, it works fine.
Now I need a query that will tell me the current rank of a user in the show view. Is it possible?
You could add a “rank” to your query and use it as sub-select. In the surrounding query use where to get your user:
Consider caching the rank of your user because subquerys are “expensive” (take long time to run/need much memory).