给定表:
Log Table: id, user_id, points, created_at
目标是回到 4 周前,每周获得到该点的累积积分:
"05/29/2017", total_points (= the Big Bang to this date)
"06/5/2017", total_points (= the Big Bang to this date)
"06/12/2017", total_points (= the Big Bang to this date)
"06/19/2017", total_points (= the Big Bang to this date)
使用 Ruby/Rails5,如何遍历最近 4 周并收集点数?
谢谢
您可以在循环中使用简单的 ActiveRecord 查询
points = (1..4).map do |n|
Log.where("created_at <= ?", n.weeks.ago).sum(:points)
end
n.weeks.ago
将转换为日期对象,这要归功于ActiveSupport。
例如:
2.weeks.ago => 2017-06-07 16:45:33
编辑:
我刚刚在评论中读到您要考虑整个星期(周一至周日(,并且第一周应该是本周。
尝试:
points = (0..3).map do |n|
Log.where("created_at <= ?", n.weeks.ago.end_of_week).sum(:points)
end