如何计算每个月末的排行榜

时间:2014-02-11 09:34:48

标签: ruby-on-rails ruby

我有一张表,记录员工一个月内收到的票数

[<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位等)。

我要将列:位置添加到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

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

1 个答案:

答案 0 :(得分:2)

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

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