2

我有一个这样的模型:

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
4

1 回答 1

1

类方法将不起作用,因为Event.range(4.months.ago, Time.now).daily需要每天根据标准定义方法,并且范围将不起作用,因为范围需要返回一个标准。目前你最好的选择是每天创建一个类方法并像使用它一样使用它Event.daily(start, finish)

class Event
  include Mongoid::Document
  include Mongoid::Timestamps

  scope :range,  lambda {|start, finish| 
    where(:created_at => {'$gte' => start,'$lt' => finish}) if start && finish
  }

  def self.daily(start, finish)
    daily_events = {}
    self.range(start, finish).each do |event|
      date_str = event.created_at.to_date.to_s
      daily_events[date_str] ||= 0
      daily_events[date_str] += 1
    end
    return daily_events
  end
end
于 2012-04-19T11:56:28.753 回答