我有一个这样的模型:
class Event
include Mongoid::Document
include Mongoid::Timestamps
scope :range, lambda {|start, finish|
where(:created_at => {'$gte' => start,'$lt' => finish}) if start && finish
}
end
我需要按事件发生日期分组的事件数量的哈希值:
{"2011-11-07"=>2, "2011-10-25"=>10, "2011-04-03"=>1, "2011-05-13"=>1, "2011-03-23"=>1, "2011-11-08"=>4, "2011-06-12"=>1, "2011-10-26"=>6}
我可以使用这个相当笨重的链从控制台中得到准确的信息:
Event.range(4.months.ago, Time.now).to_a.
group_by{ |e| e.created_at.to_date }.
map{ |date, events| [date.to_s, events.count]}.
inject({}) { |r, i| r[i.first] = i.last; r }
我真的很想把它放到一个范围或类方法中,这样我就可以写:
Event.range(4.months.ago, Time.now).daily
关于如何做到这一点的任何想法?
更新:
仅供参考,我已经尝试了以下每种解决方案。
scope :daily, lambda { to_a.group_by{ |e| e.created_at.to_date }.
map{ |date, events| [date.to_s, events.count]}.
inject(ActiveSupport::OrderedHash.new) { |r, i| r[i.first] = i.last; r } }
和
def self.daily
to_a.group_by{ |e| e.created_at.to_date }.
map{ |date, events| [date.to_s, events.count]}.
inject(ActiveSupport::OrderedHash.new) { |r, i| r[i.first] = i.last; r }
end
两者都失败了。回溯:
> Event.range(2.week.ago, Time.now).daily
/my_app/event.rb:37: warning: default `to_a' will be obsolete
NoMethodError: undefined method `created_at' for Event:Class
from /my_app/event.rb:37:in `daily'
from /var/bundler/turtle/ruby/1.8/gems/activesupport-3.0.7/lib/active_support/core_ext/enumerable.rb:26:in `group_by'
from /var/bundler/turtle/ruby/1.8/gems/activesupport-3.0.7/lib/active_support/core_ext/enumerable.rb:25:in `each'
from /var/bundler/turtle/ruby/1.8/gems/activesupport-3.0.7/lib/active_support/core_ext/enumerable.rb:25:in `group_by'
from /my_app/event.rb:37:in `daily'
from /var/bundler/turtle/ruby/1.8/gems/mongoid-2.2.0/lib/mongoid/criteria.rb:366:in `send'
from /var/bundler/turtle/ruby/1.8/gems/mongoid-2.2.0/lib/mongoid/criteria.rb:366:in `method_missing'
from /var/bundler/turtle/ruby/1.8/gems/mongoid-2.2.0/lib/mongoid/named_scope.rb:120:in `with_scope'
from /var/bundler/turtle/ruby/1.8/gems/mongoid-2.2.0/lib/mongoid/criteria.rb:365:in `send'
from /var/bundler/turtle/ruby/1.8/gems/mongoid-2.2.0/lib/mongoid/criteria.rb:365:in `method_missing'
from (irb):57
from :0