I have a voting system. Each vote has a score.
I want to be able to count how many votes were made per day?
The code below adds the scores of each vote for each day and returns a hash with the total and the date as a key:
ratings = where(created_at: start.beginning_of_day..Time.zone.now).group("created_at").select("created_at, sum(score) as total_score")
ratings.each_with_object({}) do |rating, scores|
scores[rating.created_at.to_date] = rating.total_score
end
I want to be able to count how many votes were made on each day. Any ideas?
You can do what you want using a much nicer syntax:
from = start.beginning_of_day
to = Time.zone.now
Rating.group('date(created_at)').where(created_at: from .. to).count(:score)
This will return a hash having the date(created_at) as a key and count(:score) as value, for each day.
Example: { "2014-01-21" => 100, "2014-01-22" => 1213 }
The corresponding SQL is:
SELECT COUNT("ratings"."score") AS count_score, date(created_at) AS date_created_at FROM "ratings" WHERE ("ratings"."created_at" BETWEEN '2014-01-21' AND '2014-01-24') GROUP BY date(created_at)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With