【问题标题】:undefined method `group_by_day' - rails 3.2未定义的方法“group_by_day”-rails 3.2
【发布时间】:2013-11-04 07:11:05
【问题描述】:

我想使用 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'

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,我检查了 gem,这正是我所缺少的。
    • 但是有些东西我不明白,为什么我不能从另一个表访问属性。例如:,由此我想访问用户所在城市的名称。不工作,我在这里做错了什么?
    • @ben 我想你的意思是统计每个城市的用户数,或许你可以试试User.includes(:city).group("city.name").count
    • 当然。似乎 User.includes(:city).group("city.name").count 比 User.join(:city).group("city.name").count 更好,因为它还包括那些具有没有城市。谢谢
    • 您也可以查看并帮助:stackoverflow.com/questions/19797869/…
    【解决方案2】:

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

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

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

    User.all.group_by(&:created_at)
    

    另外,我不确定最后的 .count 是否符合您的预期。它计算日期的组(在 created_at 的情况下,它会为每条记录返回几乎一个项目,因为 created_at 几乎没有重复)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2012-03-15
    • 2013-04-09
    • 2013-02-04
    • 2016-08-16
    相关资源
    最近更新 更多