我有一个投票系统。每次投票都有一个分数。
我希望能算出每天有多少票?
下面的代码会添加每天每个投票的得分,并返回一个以总数和日期为关键字的哈希值:
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
我希望能够计算每天投票数。有什么想法吗?
答案 0 :(得分:11)
您可以使用更好的语法来执行您想要的操作:
from = start.beginning_of_day
to = Time.zone.now
Rating.group('date(created_at)').where(created_at: from .. to).count(:score)
这将返回一个哈希,其日期(created_at)为关键字,并且每天计数(:得分)为值。
实施例: {“2014-01-21”=> 100,“2014-01-22”=> 1213}
相应的SQL是:
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)
答案 1 :(得分:0)
相应的MySQL查询将是
SELECT date(created_at) as date, count(*) as count FROM `ratings` WHERE (created_at between '2014-01-21 00:00:00' AND '2014-01-24 08:16:46') GROUP BY date(created_at)
Rails版本是:
start_date = Date.parse("2014-01-21").beginning_of_day
end_time = Time.zone.now
Rating.group('date(created_at)').select('date(created_at) as date, count(*) as count').where(["created_at between ? AND ?", start_time, end_time])