【问题标题】:Rails Active Record - counter_cache to return records only from a given period of timeRails Active Record - counter_cache 仅返回给定时间段的记录
【发布时间】:2017-09-01 16:26:14
【问题描述】:

我有一个拥有_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 中存储的数据用于此目的?

【问题讨论】:

    标签: ruby-on-rails database activerecord counter-cache


    【解决方案1】:

    这个怎么样:

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

    它为您提供一个哈希,其中键是用户,值是文章数,按文章数排名前 50 位的用户,按文章数降序排列。

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

    【讨论】:

    • 谢谢大卫。不知何故,我认为可能有一种 ActiveRecord 方法来实现它,但你建议的方法肯定比我原来的方法要好。
    【解决方案2】:

    这似乎更整洁:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2020-02-09
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多