【问题标题】:How to calculate leaderboard at the end of every month如何计算每个月底的排行榜
【发布时间】:2014-02-11 09:34:47
【问题描述】:

我有一张表格,可以记录员工在一个月内获得了多少票

[<Placement id: 1, employee_id: 1, month: "2014-02-01", votes: 2>, 
<Placement id: 2, employee_id: 1, month: "2014-01-01", votes: 2>, 
<Placement id: 3, employee_id: 2, month: "2014-02-01", votes: 1>,
<Placement id: 4, employee_id: 2, month: "2014-01-01", votes: 3>
<Placement id: 5, employee_id: 3, month: "2014-02-01", votes: 9>]

我现在想跟踪他们在每个月底的位置(位置 1 中的大多数投票等)。

我要像这样将 :position 列添加到 Placements 模型中:

[<Placement id: 1, employee_id: 1, month: "2014-02-01", votes: 2, position: 2>, 
<Placement id: 2, employee_id: 1, month: "2014-01-01", votes: 2, position: 2>, 
<Placement id: 3, employee_id: 2, month: "2014-02-01", votes: 1, position: 3>,
<Placement id: 4, employee_id: 2, month: "2014-01-01", votes: 3, position: 1>
<Placement id: 5, employee_id: 3, month: "2014-02-01", votes: 9, position: 1>]

我在 heroku 调度器中有这样的东西:

if Date.today == Date.today.end_of_month
 Placement.each_with_index do |p, index|
  p.update_attributes(position: index+1)
 end
end

如何比较所有相同月份的投票?这会比较所有月份

【问题讨论】:

  • 你可以通过 cron 作业来完成。
  • 这个“职位”系统是如何工作的?根据什么计算位置?为什么单个员工在一个月内有多个条目?为什么可以多次出现一个位置(位置 1 对应 id 4 和 5)?我只想添加一个表格,其中包含一个月后的职位和票数。但很大程度上取决于这实际上是如何工作的。
  • 单个员工一个月内有多条记录?
  • 排名基于每月最多投票

标签: ruby-on-rails ruby


【解决方案1】:

要在一个月内运行并更新位置,您可以:

def update_single_month(month)
  Placement.where(month: month).order('votes desc').each_with_index do |placement, position|
    placement.position = position
    placement.save!
  end
end

要在所有现有数据上运行,您只需要知道您已经拥有哪些月份的数据:

def update_all_months
  Placement.select(:month).group(:month).each { |r| update_single_month(r.month) }
end

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多