由周/月/等及放大器分组; ActiveRecord的? [英] 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...}
或者是有一些更好的办法?
or is there some better way?
感谢! 奥伦
推荐答案
在这种情况下,对我来说最好的解决办法是要么做直SQL,或者使用ActiveRecord的GROUP_BY功能:
In this case, the best solution for me was to either do it in straight SQL, or to use the activerecord group_by function:
@user.all.group_by{ |u| u.created_at.beginning_of_month }
这篇关于由周/月/等及放大器分组; ActiveRecord的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!