1

I am trying to implement user ranking with mongodb. So user has two fields:

  field :score, type: Integer, :default => 0
  field :solution_count, type: Integer, :default => 0

and to list all the users in the score table one can easily do smth like this:

User.desc(:score, :solution_count).page(params[:page])

But the question is: How to display user rank in user page?

It is obvious that we need to store rank but where and how to update it properly?

The easiest way to do it is smth like this:

# in user.rb
field :rank, type: Integer

# add rake task and execute is with Cron every 10 minutes for example
task :build => :environment do
   User.desc(:score, :solution_count).each_with_index do |user, position|
     user.update_attribute(:rank, position + 1)
   end
end

Any ideas how to implement it better?

makaroni4
  • 2,281
  • 1
  • 18
  • 26

1 Answers1

1

If you don't need to query by rank, then you can calculate it on the fly. Let's say, your page size is 20 and you're getting first page. Then users on it will have ranks from 1 to 20. Users on next page will have ranks 21-40. And so on.

page_no = params[:page].to_i
users = User.desc(:score, :solution_count).page(page_no)
users.each_with_index do |u, idx|
  u.rank = (page_no * page_size) + idx + 1
end

# go on and display users with ranks. 
<%= u.rank %>
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367