Rails Active Record - counter_cache 到 return 仅在给定时间段内记录

Rails Active Record - counter_cache to return records only from a given period of time

我有一个 has_many 文章的用户。我使用计数器缓存来存储用户曾经发表的文章数量。

class User < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
end

我使用以下语法查找发表文章最多的用户:

User.order( "articles_count desc" ).limit(50).all  

我想做的是检查过去一个月发表文章最多的 50 个顶级用户。

我知道我可以像这样获取每个用户上个月发表的文章数量,但感觉效率不高:

User.find_each do |user|
  user.articles.where('created_at >= ?', 1.week.ago.utc).count
end

我尝试了一些 SQL 查询,但运气不佳,想知道是否可以使用存储在我的 counter_cache 中的数据来达到这个目的?

这个怎么样:

Article.
  includes(:user).
  where('created_at >= ?', 1.week.ago.utc).
  group(:user).
  order("count(*) desc").
  limit(50).
  count

给你一个散列,key是用户,value是文章数,文章数前50的用户,按文章数降序排列。

created_at 上放置一个索引,也许 user_id 也可以。

这个好像稍微整齐一点:

User.
joins(:articles).
where('articles.created_at >= ?', 1.week.ago.utc).
group('articles.user_id').
order("count(*) desc").
limit(50)