I have a user model and a bid model. I want the user to know what their rank is based upon a score stored as a method, i.e. “3/7” based upon user.score method. Currently, I’m trying to tuck this geek_rank method into the Bid model as:
def user_rank(my_id)
#Finds all bids associated with parent ticket object
bids = Bid.find_by_ticket_id(self.ticket.id)
bids = bids.sort_by { |b| b.user.score}
i = 0
for b in bids
i += 1
if b.user_id.to_i == my_id.to_i
myrank = i
end
end
user_rank = myrank.to_s + "/" + i.to_s
end
For some reason the sort_by method works in the controller but not when I try to sort in the model. Can anyone tell me what the problem is along with how my code sucks? 🙂
TO CLARIFY:
The actual error I’m getting is a method missing error.
The method
find_by_ticket_idDOES not return an array; it returns a Bid.Use
find_all_by_ticket_idinstead.I would rewrite your method as follows:
In this approach most of the calculation is done by the DB.
Caveat 1
This method will return the same rank for people with the same score.
E.g:
Caveat 2
This solution performs better than your solution. But it still requires n * 3 round trips to the server to calculate the rank. Solution can be further optimized to calculate the rank of all the users in one SQL.
Articles about rank calculation optimization:
Article 1