42

我正在我的产品中进行一些静态计算。用户执行了许多操作,比如说发布的评论。我希望能够向他们展示他们在过去一个月中每周发布了多少评论,或者在过去一年中每月发布了多少评论。

activerecord 有什么办法可以这样分组吗?我最好的办法是简单地手动执行此操作 - 根据我自己的标准迭代记录总和吗?

class User < ActiveRecord::Base
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :user
end

@user.comments(:all).map {|c| ...do my calculations here...}

还是有更好的方法?

谢谢!奥伦

4

7 回答 7

91

在 Postgres 中,您可以执行以下操作:

@user.comments.group("DATE_TRUNC('month', created_at)").count

要得到:

{"2012-08-01 00:00:00"=>152, "2012-07-01 00:00:00"=>57, "2012-09-01 00:00:00"=>132}

它接受从“微秒”到“千年”的值进行分组: http ://www.postgresql.org/docs/8.1/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC

于 2012-09-21T11:38:37.667 回答
31

在这种情况下,对我来说最好的解决方案是直接使用 SQL,或者使用 Ruby group_by 函数:

@user.all.group_by{ |u| u.created_at.beginning_of_month }
于 2010-01-11T22:40:33.907 回答
25

这是更精致的版本

@user.comments.group("year(created_at)").group("month(created_at)").count
于 2014-05-28T07:30:12.390 回答
13

我的猜测是这样的:

@user.comments.count(:group => "year(created_at),month(created_at)")

干代码,ymmv

于 2009-05-24T04:17:42.713 回答
4

使用 group_by

@user.comments.group_by(&:week)

class User < ActiveRecord::Base
  def week
    some_attribute_like_date.strftime('%Y-%W')
  end
end

这将为您提供 YYYY-WW 格式的分组列表

于 2014-09-05T12:37:35.557 回答
2

查看 has_activity 插件。

于 2009-05-24T16:20:57.263 回答
2

查看团体约会宝石

https://github.com/ankane/groupdate

它有最近的提交,与 postgresql 一起使用,与 chart kick 轻松集成以实现快速图表,并与时区一起使用!!

于 2015-02-04T21:02:22.370 回答