简体   繁体   中英

How do I use the sorted unique ids in redis to display users?

I am trying to create a highscore board for my Users. I am using redis-objects gem for this task.

class User < ActiveRecord::Base
  include Redis::Objects
  sorted_set :leaderboard, global: true
  after_update :update_leaderboard

    def update_leaderboard
      self.class.leaderboard[id] = score
    end
end

With this method, I got the user ids and sorted by their score everytime I update the scores.

User.leaderboard.revrange(0,2) #["3", "1", "2"]

My question:

How can I make use of the arrays of sorted ids, and display my users based on the order? Lets say I want to sort my users in index page.

class UserController < ApplicationController
  def index
  @users = User.all
  end
end

Thanks.

The find method will take an array, but sorting is a problem... if you don't mind sorting at the app level...

class UserController < ApplicationController
  def index
    arr = User.leaderboard.revrange(0,2)
    @users = User.find(arr).sort_by{|user| arr.index user.id}
  end
end

Someone may have a better solution...

You could do this:

class UserController < ApplicationController
  def index
    ids = User.leaderboard.revrange(0,2)
    @users = User.all.sort_by { |u| ids.index(u.id) }
  end
end

For more information sorting-an-array-of-objects-given-an-ordered-list-of-ids

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM