【发布时间】: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