在我的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 |
+-------------------------+---------+----------+
我希望按日期范围管理一批关税,而不是单独管理每条记录。
如何按上述日期范围对值进行分组?
答案 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=>[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