【发布时间】:2011-03-30 05:27:09
【问题描述】:
在控制台中玩了很多之后,我想出了这个方法来按它们发生的日期对类似 activerecord(Mongoid)的对象进行分组。我不确定这是实现这一目标的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个好方法吗?
#events is an array of activerecord-like objects that include a time attribute
events.map{ |event|
# convert events array into an array of hashes with the day of the month and the event
{ :number => event.time.day, :event => event }
}.reduce({}){ |memo,day|
# convert this into a hash with arrays of events keyed by their day or occurrance
( memo[day[:number]] ||= [] ) << day[:event]
memo
}
=> {
29 => [e1, e2],
28 => [e3, e4, e5],
27 => [e6, e7],
...
}
谢谢!
【问题讨论】:
-
您的问题是 MongoDB/MongoId,但您提到了 ActiveRecord。您能否澄清一下您使用的是 MongoId 还是 ActiveRecord?
-
对,我的意思是说类似于 ActiveRecord 的对象,因为 Mongoid 非常接近 ActiveRecord 的 API。已编辑。
标签: ruby-on-rails ruby mongoid grouping