ruby-on-rails - 作用域关联上的 Rails 中的 counter_cache

标签 ruby-on-rails activerecord associations named-scope counter-cache

我有 User型号has_many :notifications . Notification有一个 bool 列 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调用 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/

相关文章:

php - 如何使用 Codeigniter Active Record CI2 使用 JOINed 表更新数据?

ruby-on-rails - rails 找到 : using conditions while including same table twice via different named associations

c# - 如何使用 Entity Framework Fluent API 配置多对多关系

ruby-on-rails - 在模型文件中调用的辅助方法不起作用

css - 在公共(public)页面和管理仪表板之间拆分基本样式表

ruby-on-rails - 事件管理字段上的 bool 值返回空而不是 false (Rails 3.2/Active Admin)

ruby-on-rails - Heroku ActionView::Template::/app/app/assets/javascripts/application.js 中的错误 eof (未定义)

ruby-on-rails - Rails : Calling . limit(5) 更改结果顺序

hibernate - Hibernate标准中的关联大小

ruby-on-rails - Rails 与多个相同关系实例的关联