我有 User
型号has_many :notifications
. Notification
有一个 bool 列 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
调用 Notification
.但是,如果我想缓存用户拥有的未见通知的数量怎么办? IE。缓存
unseen_notifications.size
而不是 notifications.size
?是否有内置方法可以使用 counter_cache
执行此操作还是我必须推出自己的解决方案?
最佳答案
根据 this blog post ,没有内置的方法可以将计数器缓存用于范围关联:
ActiveRecord’s counter cache callbacks only fire when creating or destroying records, so adding a counter cache on a scoped association won’t work. For advanced cases, like only counting the number of published responses, check out the 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
另请参阅 Counter Cache for a column with conditions? 的答案有关此方法的其他实现示例。
关于ruby-on-rails - 作用域关联上的 Rails 中的 counter_cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37029847/