未定义的方法 `group_by_day' - Rails 3.2

5

我想使用 chartkick 制作每天用户注册数量的折线图,这只需要一行代码,但是它出现了错误。

`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'
2个回答

10
要支持 group_by_day,需要安装一个额外的 gem: groupdate,该 gem 由 Chartkick 的作者编写。

非常感谢,我检查了宝石并且它就是我所缺少的。 - ben
但是有一件事我不明白,为什么我不能从另一个表中访问属性。例如:<%= pie_chart User.city.group("name").count %>,我想要访问用户所在城市的名称。但是它不起作用,我做错了什么? - ben
1
@ben 我想你的意思是统计每个城市的用户数量,你可以尝试使用 User.includes(:city).group("city.name").count - Mifeng
当然。看起来 User.includes(:city).group("city.name").count 比 User.join(:city).group("city.name").count 更好,因为它还包括那些没有城市的用户。谢谢。 - ben
你也可以查看并帮助解决这个问题:http://stackoverflow.com/questions/19797869/making-a-pie-chart-of-the-user-age-in-rails - ben

2
我看不到group_by_day方法的定义,这不是一个标准方法。也许你引用的是group_by
无论如何,group_by未在ActiveRecord类中定义,而是在array中定义。
首先,您需要将记录提取到数组中。另外,如果created_at是一个方法,您需要使用&传递它。
User.all.group_by(&:created_at)

此外,我不确定末尾的.count是否按您的预期运行。它正在计算日期组数(对于created_at而言,由于几乎不会重复,它将为每个记录返回几乎一个项目)。

你说得对,我从我的评论中来,没有注意到错误的方法名称。https://dev59.com/TG445IYBdhLWcg3wM3fx#4987487 我已经更新了答案。 - Simone Carletti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接