[英]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.
我正在为此任务使用redis-objects gem。
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. 使用这种方法,每次更新分数时,我都会得到用户ID并按分数排序。
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? 如何使用已排序ID的数组,并根据顺序显示用户? 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... find
方法将采用数组,但是排序是一个问题...如果您不介意在应用程序级别进行排序...
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 有关更多信息,请对给定的ID排序的对象数组进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.