【问题标题】:counter_cache in Rails on a scoped association作用域关联上 Rails 中的 counter_cache
【发布时间】:2016-05-04 13:52:40
【问题描述】:

我有User 模型has_many :notificationsNotification 有一个布尔列 seen 和一个名为 :unseen 的范围,它返回 seenfalse 的所有通知。

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


【解决方案1】:

根据this blog post,没有内置方法可以将计数器缓存用于范围关联:

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? 的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多