Rails中针对作用域关联的counter_cache

12

我有一个User模型,它has_many :notificationsNotification有一个布尔列seen和一个叫做:unseen的作用域,它返回所有seenfalse的通知。

class User < ApplicationRecord
  has_many :notifications
  has_many :unseen_notifications, -> { unseen }, class_name: "Notification"
end
我知道如果我为users添加一个名为notifications_count的列,并在Notificationbelongs_to调用中添加counter_cache: true,就可以缓存通知的数量。

但是如果我想要缓存用户拥有的未读通知的数量,该怎么办?即缓存unseen_notifications.size而不是notifications.size?是否有内置的方法可以使用counter_cache来实现这一点,还是我必须自己编写解决方案?


1
据我所知,没有内置的方法可以做到这一点。但是你可以尝试使用counter_culture gem。它可能符合你的需求。 - Van Huy
1个回答

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

此外,还可以查看Counter Cache for a column with conditions?的答案,以获取这种方法的其他实现示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接