In a Rails app, I have a User model and a Posts model.
I have a :post_rate method
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
This shows the percentage of days a User posted in a given time frame.
On a User show page I want to display a summary of the user’s post frequency by month. I need an array that looks like:
['Month', 'Frequency'],
['Jan', 0.1],
['Feb', 0.5],
['Mar', 0.9],
etc..
(the labels and titles are needed).
How can I achieve this?
What performance considerations do I need to think about?
Thanks
If your rails is recent enough, you can use ActiveRecord’s query smarts to compile a query that does this in SQL. You can pass a function to a GROUP BY clause via
group:The above works for PostgreSQL. You may have to change the arg to
groupto get it to work with a different database.The result will be in the form of a hash whose keys are the GROUP BY column and whose values are the counts. You will probably need to do some munging to get the data in the format you require.