在Rails应用程序中,我有一个User模型和一个Posts模型。
我有一个:post_rate
方法
def self.post_rate(month_start, month_end)
where('created_at >= ? AND <= ?', month_start, month_end).map { |p| p.created_at.beginning_of_day }.uniq.size.to_f / (month_start - month_end).to_f
end
显示用户在给定时间范围内发布的天数百分比。
在用户显示页面上,我想按月显示用户发布频率的摘要。我需要一个看起来像这样的数组:
['Month', 'Frequency'],
['Jan', 0.1],
['Feb', 0.5],
['Mar', 0.9],
etc..
(需要标签和标题)。
我怎样才能做到这一点?
我需要考虑哪些性能因素?
由于
答案 0 :(得分:1)
如果您的rails足够新,您可以使用ActiveRecord的查询智能来编译在SQL中执行此操作的查询。您可以通过group
将函数传递给GROUP BY子句:
where('created_at >= ? AND <= ?', month_start, month_end).group("to_char(created_at,'MONTH')").count()
以上适用于PostgreSQL。您可能必须将arg更改为group
以使其与其他数据库一起使用。
结果将采用散列的形式,其键是GROUP BY列,其值是计数。您可能需要进行一些调整以获得所需格式的数据。