[英]In rails, given an array of Point objects, how do I sum the point values for each player?
We're using postgres for this project. 我们正在为此项目使用postgres。
The goal is to get a hash which pairs each player with the sum of their point values. 目的是获得一个散列,将每个玩家与其得分值的总和配对。
I have an array of Point
objects which looks something like this: 我有一个
Point
对象数组,看起来像这样:
( Note : each hash here is actually a database object from Points.where
. The array is actually an ActiveRecord:Relation
instance) ( 注意 :这里的每个哈希实际上是
Points.where
的数据库对象。数组实际上是ActiveRecord:Relation
实例)
[
{ value: 3, player_id: 55 },
{ value: 1, player_id: 21 },
{ value: 2, player_id: 55 },
{ value: 6, player_id: 23 },
{ value: 2, player_id: 78 },
{ value: 2, player_id: 55 },
{ value: 5, player_id: 80 },
{ value: 7, player_id: 21 },
{ value: 2, player_id: 23 },
{ value: 1, player_id: 78 },
{ value: 4, player_id: 80 }
]
The expected output of this would be something like this: 预期的输出将是这样的:
{
55: 7,
21: 8,
23: 8,
78: 3,
80: 9
}
Where the key is the player_id, and the value is the sum of all of their point values. 其中键是player_id,值是它们所有点值的总和。
One solution in ruby I came up with uses activerecord to sum the points for each ID in the set. 我想出的一种红宝石解决方案是使用activerecord对集合中每个ID的点求和。
points = get_the_points()
point_map = {}
ids = points.pluck(:player_id)
player_ids.each do |id|
points_for_id = points.where(player_id: id).pluck(:value)
sum_of_points = points_for_id.sum
point_map[id] = sum_of_points
end
return point_map
But I know this can be done with SQL, and I know it'll be faster. 但是我知道这可以使用SQL来完成,而且我知道它会更快。
Because I'm just dealing with one model, I don't have to use joins or anything, do I? 因为我只处理一种模型,所以不必使用联接或其他任何方法,对吗?
尝试一个SQL查询
Point.group(:player_id).sum(:value)
In plain SQL we would want something like: 在普通的SQL中,我们想要这样的东西:
SELECT points.user_id, SUM(points.value) AS sum_value
FROM points
GROUP BY points.user_id;
Which groups the rows by user_id
and fetches an aggregate of points.value
. 哪个按
user_id
对行进行分组并获取points.value
的集合。
user_id | sum_value
---------+-----------
14 | 18
25 | 19
17 | 29
12 | 14
8 | 9
1 | 16
15 | 19
10 | 37
11 | 26
4 | 43
To get the same query in Rails you would use: 要在Rails中获得相同的查询,您可以使用:
Point.group(:user_id).sum(:value)
Because I'm just dealing with one model, I don't have to use joins or anything, do I?
因为我只处理一种模型,所以不必使用联接或其他任何方法,对吗?
Not unless you want to do something like a high score list where you list the users name and score. 除非您想执行类似高分列表的操作,否则您要在其中列出用户名和得分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.