我正试图为我的用户创建一个高分板。我正在使用redis-objects宝石来完成这项任务。
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使用这种方法,每次更新分数时,我都会得到用户I并按他们的分数排序。
User.leaderboard.revrange(0,2) #["3", "1", "2"]我的问题是:
如何利用排序I的数组,并根据订单显示用户?假设我想在索引页面中对我的用户进行排序。
class UserController < ApplicationController
def index
@users = User.all
end
end谢谢。
发布于 2015-10-04 10:41:01
你可以这样做:
class UserController < ApplicationController
def index
ids = User.leaderboard.revrange(0,2)
@users = User.all.sort_by { |u| ids.index(u.id) }
end
end有关更多信息,sorting-an-array-of-objects-given-an-ordered-list-of-ids
发布于 2015-10-04 09:51:46
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也许有人有更好的解决方案..。
https://stackoverflow.com/questions/32931899
复制相似问题