对象和计算的总和

问题描述 投票:0回答:1

我有统计模型:

Stat(id: integer, points: float, user_id: integer, match_id: integer)

现在这是我的代码:

stat = Stat.where.not(points: 0).group(:user_id).sum("points")

我需要的是获得每个玩家的积分总和然后得到他们有多少匹配(积分/匹配计数的总和)。使用上面的代码我只能得到每个玩家的总和。

编辑

Stat(id: integer, points: float, user_id: integer, match_id: integer, team_id: integer)

对于匹配模型:

 Match(id: integer, team_a_id: integer, team_b_id: integer)

编辑

这是我现在的代码:

stat.each do |f|
  new_value = (f.sum_points.to_f / f.matches_count.to_f)
  f.sum_points = new_value.round(2)
  a << f
end

new_stat = a.sort_by(&:sum_points).reverse.first(10).flatten

我必须在每个数据上更改sum_points的值,如果我获得了大量数据,那么需要时间是否有办法将其最小化?我需要的是第一个前10名。

ruby-on-rails ruby ruby-on-rails-5
1个回答
3
投票

我假设,每个stat都有唯一的user_idmatch_id对,那么下面的请求就可以了:

Stat
  .group(:user_id)
  .select("user_id, count(*) as matches_count, sum(points) as sum_points")

因此,您将收到以下对象的集合:

#<ActiveRecord::Relation [#<Stat id: nil, user_id: 1>, #<Stat id: nil, user_id: 2>]>

每个对象都有sum_pointsmatches_count方法:

stats = Stat
  .group(:user_id)
  .select("user_id, count(*) as matches_count, sum(points) as sum_points")

stats.first.user_id # => returns user_id
stats.first.matches_count # => returns the number of matches played
stats.first.sum_points # => returns the number of points earned
© www.soinside.com 2019 - 2024. All rights reserved.