如何显示整个星期而不是一天的趋势剪辑?

How to display trending clips for the entire week, instead of the day?

所以,我有一个应用程序可以跟踪每个剪辑的观看次数,这样我们就可以显示当天的热门剪辑。但是,由于用户群仍然相对较小,我们希望显示本周的热门剪辑。

这是我们当前的代码:

# trending slider
    today_clips = Clip.joins(:clip_views).where(clip_views: {viewed_at: Date.today}).keep_if{|c| (c.film.active)}.uniq.map{|c| [c.id, c.clip_views.count]}
    ordered_clips = today_clips.sort {|a, b| b[1] <=> a[1]}
    @trending_clips = []
    if ordered_clips.present?
      ordered_clips.map{|a| a[0]}.each do |i|
        @trending_clips << Clip.find(i)
      end
      @trending_clips.keep_if{|c| (c.film.active)}
    end

如何更改上述代码以显示整周的趋势剪辑,而不是每天重置?

谢谢!

你可以简单地改变

.where(clip_views: {viewed_at: Date.today})
# => WHERE clip_views."viewed_at" = '2015-01-26'

.where(clip_views: {viewed_at: 1.week.ago..Date.today})
# => WHERE clip_views."viewed_at" BETWEEN '2015-01-19 16:45:02.537752' AND '2015-01-26'

它不会搜索特定日期的观看次数,而是搜索某个时间范围内的观看次数。

尝试将您想要的范围传递到您的 where 子句中:

weekly_clips = Clip.joins(:clip_views)
                   .where(clip_views: {viewed_at: 1.week.ago..Date.today})
                   .keep_if{|c| (c.film.active)}
                   .uniq
                   .map{|c| [c.id, c.clip_views.count]}
ordered_clips = weekly_clips.sort {|a, b| b[1] <=> a[1]}
@trending_clips = []
if ordered_clips.present?
  ordered_clips.map{|a| a[0]}.each do |i|
    @trending_clips << Clip.find(i)
  end
  @trending_clips.keep_if{|c| (c.film.active)}
end