undefined方法`group_by_day’ – rails 3.2

我想使用chartkick制作一个用户注册数量(每天)的折线图 ,这是一个简单的一行代码,但它给出了一个错误

`undefined method `group_by_day' for #` 

在我看来,我有

  

错误日志:

 Rendered admin/dashboards/index.html.erb within layouts/application (145.2ms) Completed 500 Internal Server Error in 1018ms NoMethodError - undefined method `group_by_day' for #: activerecord (3.2.14) lib/active_record/dynamic_matchers.rb:55:in `method_missing' app/views/admin/dashboards/index.html.erb:38:in `_app_views_admin_dashboards_index_html_erb___3330517857505238097_39214860' actionpack (3.2.14) lib/action_view/template.rb:145:in `block in render' activesupport (3.2.14) lib/active_support/notifications.rb:125:in `instrument' actionpack (3.2.14) lib/action_view/template.rb:143:in `render' actionpack (3.2.14) lib/action_view/renderer/template_renderer.rb:48:in `block (2 levels) in render_template' actionpack (3.2.14) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument' activesupport (3.2.14) lib/active_support/notifications.rb:123:in `block in instrument' activesupport (3.2.14) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (3.2.14) lib/active_support/notifications.rb:123:in `instrument' actionpack (3.2.14) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument' 

要支持group_by_day ,您需要捆绑来自Chartkick的同一作者的另一个gem:groupdate。

我看不到group_by_day方法的定义。 这不是标准方法。 可能是你引用了group_by

在任何情况下,都没有为ActiveRecord类定义group_by 。 它是在array上定义的。

首先必须将记录提取到数组中。 另外,如果created_at是一个方法,则需要传递使用&。

 User.all.group_by(&:created_at) 

另外,我不确定最终的.count是否符合您的预期。 它计算日期的组(如果是created_at,它将为每条记录返回几乎一个项目,因为created_at实际上很难重复)

大概你需要这样的数据结构:

 { '2013-01-01' => 6, '2013-01-11' => 23, ... } 

其中键是日期,值是该日期的注册数。

在我能找到的任何地方都没有group_by_day方法。 但是,您可以在数据库(它所属的位置)内轻松完成此操作:

 counts = User.group('date(created_at)').count 

或等效地:

 counts = User.count(:group => 'date(created_at)') 

这两个都会向数据库发送一个看起来或多或少像这样的请求:

 select count(*), date(created_at) from users group by date(created_at) 

date(created_at)应该在PostgreSQL和MySQL中工作相同,我不确定其他数据库。