2013-11-04 53 views
2

我想使用户注册等的(每天)使用chartkick,它是一个简单的一行代码的数量的线图,但它是给一个错误未定义的方法`group_by_day” - 轨道3.2

`undefined method `group_by_day' for #<Class:0x00000004b4fbf0>` 

在我的意见我有

<%= line_chart User.group_by_day(:created_at).count %> 

错误日志:

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 #<Class:0x00000004b4fbf0>: 
    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' 

回答

5

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

+0

非常感谢,我检查了宝石,这是我失踪。 – ben

+0

但有一些我不明白,为什么不能从另一个表访问属性。例如:<%= pie_chart User.city.group(“name”)。count%>,从此我想访问用户的城市名称。不工作,我在这里做错了什么? – ben

+1

@ben我认为你的意思是计算每个城市的用户数量,可能你可以尝试'User.includes(:city).group(“city.name”)。count' – Mifeng

2

我看不到group_by_day方法的定义。这不是一种标准方法。可能你是参考group_by

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

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

User.all.group_by(&:created_at) 

此外,我不确定最后的.count表现如您所料。它的票的日期组(和created_at的情况下,它会返回几乎每一件记录,因为created_at真的很难复制)

+0

你是对的,我来自一个评论我的问题,我没有注意到错误的方法名称。 http://stackoverflow.com/questions/4987392/how-do-i-group-by-day-instead-of-date/4987487我更新了答案。 –

0

想必你需要一个数据结构是这样的:

{ '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一样,我不知道其他数据库。

相关问题