ruby-on-rails - 使用我的排行榜。可以最大限度地减少工作量

标签 ruby-on-rails ruby ruby-on-rails-5

我有统计模型:

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= Stat
.group(:user_id)
.select("user_id, count(*) as matches_count, sum(points) as score")
.where.not(points: 0)
.where.not(match_id: nil)

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 名。

最佳答案

最有效的方法是使用 sql 计算数据并只检索前 10 个。

基本上,现在您正在手动解析整个事件记录数组以计算 sum_points,然后您正在对所有数据进行排序和反转以检索前 10 名。正如您所说,当大量数据将存储在数据库中。

这是我的解决方案,它将仅使用 sql 查询来计算和检索前 10 个:

stat = Stat.group(:user_id)
.select("user_id, round((sum(points) /count(*)), 2) as sum_points")
.where.not(points: 0).where.not(match_id: nil).order("sum_points DESC").first(10)

关于ruby-on-rails - 使用我的排行榜。可以最大限度地减少工作量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52287819/

相关文章:

ruby-on-rails - 如果函数调用返回某些东西,Ruby/Rails 返回结果

ruby-on-rails - dig 方法不能与 ActionController::Parameters 一起正常工作

ruby-on-rails - 从 Rails 5 模型访问 jsonb 列和属性

ruby-on-rails - 未应用 ActiveRecord cache_timestamp_format 配置

ruby-on-rails - 在设计 SSL Controller 之后返回到 HTTP

ruby-on-rails - 每次运行测试时,Rspec 和 Capybara 都会抛出不一致的 Postgresql 错误

mysql - 为 RoR 设置 MySQL 数据库时出错

带有引号的 Ruby 字符串用于 shell 命令参数?

ruby - 重新安装 ruby​​gems

Vim 中类似 RubyMine 的自动套用格式