简体   繁体   English

Rails按值和数组排序哈希

[英]Rails order hash by values and array

I had array of users, and array of they id's. 我有一组用户,还有一组ID。 I'm need create hash with {name => id}, but with order of id's array. 我需要使用{name => id}创建哈希,但要使用ID数组的顺序。 As example, when i wrote: 例如,当我写:

keys = [5, 3, 2, 4, 1]
users = User.all.where(id: keys).pluck(:name, :id).to_h

It's return me {"User_1"=>2, "User_2"=>3, "User_3"=>4, "User_4"=>5, "User_0"=>1} 返回我{"User_1"=>2, "User_2"=>3, "User_3"=>4, "User_4"=>5, "User_0"=>1}

But i'm need to get such thing: 但是我需要得到这样的东西:

{"User_4"=>5, "User_2"=>3, "User_1"=>2, "User_3"=>4, "User_0"=>1}

Is there opportunity to had such hash on where operation? 是否有机会在哪里进行这样的哈希运算?

The array of users that you get from your database is ordered by the updated_at column. 您从数据库中获得的用户数组按updated_at列排序。 Try this: 尝试这个:

users = User.where(id: keys).order(id: :desc).pluck(:name, :id).to_h

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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