我怎样才能按时间(HH:MM)分组mongoid或ruby
我想通过departure_at
(HH:MM)按照以下数据进行分组。
如何使用Rails或Mongoid
轻松实现期待结果:
{
'06:40': [item125, item131],
'10:20': [item126],
....
[125] #<Tiger _id: 811_0640_1010_TPE_KIX, to: "KIX", from: "TPE", price: 4899,departure_at: 08-11 06:40:00 UTC>,
[126] #<Tiger _id: 811_1020_0305_TPE_KIX, to: "KIX", from: "TPE", price: 5450,departure_at: 08-11 10:20:00 UTC>,
....
[131] #<Tiger _id: 812_0640_1010_TPE_KIX, to: "KIX", from: "TPE", price: 4899,departure_at: 08-12 06:40:00 UTC>,
答案 0 :(得分:1)
首先,创建一个["HH:MM", object]
的数组。然后你可以使用this question
array = @your_objects.map{|obj| [obj.date_departure.strftime("%H:%m"), obj]}
Hash[ array.group_by(&:first).map{ |k,a| [k,a.map(&:last)] } ]