如何按日期范围管理记录?

时间:2018-02-01 08:56:36

标签: mysql ruby-on-rails

在我的rails应用程序中,我在表tariffs的数据库中有以下结构:

  +------------+---------+
  |   Date     |  Value  |
  +------------+---------+
  | 01/01/2018 |    1    |
  | 02/01/2018 |    2    |
  | 03/01/2018 |    2    |
  | 04/01/2018 |    2    |
  | 05/01/2018 |    3    |
  | 06/01/2018 |    3    |
  | 07/01/2018 |    3    |
  | 08/01/2018 |    2    |
  +------------+---------+

在我看来,我想有这样的事情:

  +-------------------------+---------+----------+
  |           Date          |  Value  |  Actions |
  +-------------------------+---------+----------+
  | 01/01/2018 - 01/01/2018 |    1    |   Delete |
  | 02/01/2018 - 04/01/2018 |    2    |   Delete |
  | 05/01/2018 - 07/01/2018 |    3    |   Delete |
  | 08/01/2018 - 08/01/2018 |    1    |   Delete |
  +-------------------------+---------+----------+

我希望按日期范围管理一批关税,而不是单独管理每条记录。

如何按上述日期范围对值进行分组?

1 个答案:

答案 0 :(得分:1)

Tariff.all.group_by(&:value).map{
    |k, v| {k=> v.map{|elem| elem.date}}
}.reduce({}, :merge).map{
    |k, v| {k => v.minmax}
}
  1. 获取所有关税并按值(group_by
  2. 对其进行分组
  3. 将日期提取到新数组(map
  4. 将哈希数组转换为单个哈希(reduce
  5. 最后获取最短和最长日期(minmax
  6. 输出:

    [{1=>[Mon, 01 Jan 2018, Mon, 01 Jan 2018]},
    {2=>[Tue, 02 Jan 2018, Thu, 04 Jan 2018]},
    {3=>[Fri, 05 Jan 2018, Sun, 07 Jan 2018]}, ...]
    

    除了评论:

    如果我说得对,这会给你预期的输出:

    tariffs = Tariff.all
    grouped = [tariffs.first.value => [tariffs.first.date]]
    prev = nil
    tariffs.drop(1).each do |t|
        if prev.present? && t.value == prev.value
            grouped.last.values.first.push(t.date)
        else
            grouped.push(t.value => [t.date])
        end
        prev = t
    end
    
    grouped.map{|g| {g.keys.first => g.values.first.minmax}}
    

    您可以将Traffic

    的类方法包装起来