按周/月/等分组活动记录? [英] Grouping by week/month/etc & ActiveRecord?
问题描述
我正在我的产品中进行一些静力学计算.用户执行了许多操作,比如说发表评论.我希望能够向他们展示他们过去一个月每周或过去一年每月发布的评论数量.
I'm doing some statics calculation in my product. A user has performed a number of operations, let's say posted comments. I want to be able to show them how many comments they've posted per week for the past month, or per month for the past year.
activerecord 有没有办法以这种方式分组?我最好是简单地手动执行此操作 - 根据我自己的标准迭代记录总和?
Is there any way with activerecord to group this way? Is my best best to simply do this manually - to iterate over the records summing based on my own criteria?
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...}
或者有更好的方法吗?
谢谢!奥伦
推荐答案
在这种情况下,对我来说最好的解决方案是直接使用 SQL 或使用 Ruby group_by 函数:
In this case, the best solution for me was to either do it in straight SQL, or to use the Ruby group_by function:
@user.all.group_by{ |u| u.created_at.beginning_of_month }
这篇关于按周/月/等分组活动记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!