【发布时间】:2016-05-04 13:52:40
【问题描述】:
我有User 模型has_many :notifications。 Notification 有一个布尔列 seen 和一个名为 :unseen 的范围,它返回 seen 为 false 的所有通知。
class User < ApplicationRecord
has_many :notifications
has_many :unseen_notifications, -> { unseen }, class_name: "Notification"
end
我知道如果我将名为notifications_count 的列添加到users 并将counter_cache: true 添加到我在belongs_to 调用中的belongs_to 中,我可以缓存通知的数量。
但是,如果我想缓存用户拥有的 unseen 通知的数量怎么办? IE。缓存unseen_notifications.size 而不是notifications.size?是否有使用 counter_cache 的内置方法来执行此操作,还是我必须推出自己的解决方案?
【问题讨论】:
-
据我所知,没有内置的方法可以做到这一点。但是你可以试试counter_culture gem。它可能适合您的需求
标签: ruby-on-rails activerecord associations named-scope counter-cache