我有一个User
模型,它has_many :notifications
。 Notification
有一个布尔列seen
和一个叫做:unseen
的作用域,它返回所有seen
为false
的通知。
class User < ApplicationRecord
has_many :notifications
has_many :unseen_notifications, -> { unseen }, class_name: "Notification"
end
我知道如果我为users
添加一个名为notifications_count
的列,并在Notification
的belongs_to
调用中添加counter_cache: true
,就可以缓存通知的数量。
但是如果我想要缓存用户拥有的未读通知的数量,该怎么办?即缓存unseen_notifications.size
而不是notifications.size
?是否有内置的方法可以使用counter_cache
来实现这一点,还是我必须自己编写解决方案?