简体   繁体   English

如何在Redis中使用排序的唯一ID来显示用户?

[英]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.

相关问题 jQuery / Rails:如何使用jQuery修改以Rails中唯一ID结尾的多种表单的提交? - jQuery/Rails: How do I use jQuery to modify submit for multiple forms ending with unique IDs in Rails? 如何从Redis排序集中弹出? - How can I pop from a Redis sorted set? 如何在Vanity中使用现有的Redis连接? - How do I use an existing Redis connection in Vanity? 如何建立一个唯一值列表并显示其ID数组? - How to build a list of unique values and display an array of their ids? 具有设计路径的用户和管理员之间的唯一ID - Unique IDs between Users and Admins with Devise Rails Devise:用户有唯一的 url,如何防止他们使用 controller 操作路线? - Devise: Users have unique urls, how do I prevent them from using controller action routes? 我如何在Rails中使用子域将用户重定向到其域 - how do i use subdomain in rails to redirect users to thier domains 如何在Haml中制作动态ID? - How do I make dynamic ids in Haml? 如何从按其ID的特定顺序排序的记录数组中获取ActiveRecord :: Relation? - How can I get an ActiveRecord::Relation from an array of records sorted in a specific order of their IDs? Rails 4 - 如何在js.erb文件中使用div_for中的动态div ID? - Rails 4 - How do I use dynamic div ids from div_for in a js.erb file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM