Rails上的counter_cache有关作用域的关联

GMA*_*GMA 5 activerecord named-scope ruby-on-rails associations counter-cache

我有User模特哪个has_many :notifications.Notification有一个布尔列seen和一个调用的范围:unseen,它返回所有通知所在的seen位置false.

class User < ApplicationRecord
  has_many :notifications
  has_many :unseen_notifications, -> { unseen }, class_name: "Notification"
end
Run Code Online (Sandbox Code Playgroud)

我知道如果我添加一个名为to 的列并添加到我的调用中,我可以缓存通知的数量.notifications_countuserscounter_cache: truebelongs_toNotification

但是,如果我想缓存用户拥有的看不见的通知数量呢?即缓存unseen_notifications.size而不是notifications.size?有没有内置的方法来实现这一点,counter_cache还是我必须推出自己的解决方案?

Dav*_*ers 7

根据这篇博客文章,没有内置的方法可以将计数器缓存用于范围关联:

ActiveRecord 的计数器缓存回调仅在创建或销毁记录时触发,因此在作用域关联上添加计数器缓存将不起作用。对于高级案例,例如只计算已发布回复的数量,请查看counter_culture gem。

除了使用外部 gem 之外,您还可以通过向Notification模型添加回调并向模型添加整数列(例如,unseen_notifications_count)来推出自己的解决方案User

# Notification.rb
after_save    :update_counter_cache
after_destroy :update_counter_cache

def update_counter_cache
  self.user.unseen_notifications_count = self.user.unseen_notifications.size
  self.user.save
end
Run Code Online (Sandbox Code Playgroud)

另请参阅Counter Cache for a column with conditions的答案有关此方法的其他实施示例。