模块:Mongoid::Association::Referenced::CounterCache
- 扩展方式:
- ActiveSupport::Concern
- 包含在:
- Mongoid::Association
- 定义于:
- lib/mongoid/association/referenced/counter_cache.rb
Overview
Mongoid::Document 中包含的 Mixin 模块增加了在引用的 n 对多关联中缓存对方文档计数的能力。
在命名空间下定义
模块: 类方法
类方法摘要折叠
-
。 define_callbacks! (关联)⇒ 类
private
添加负责更新计数器缓存字段的回调。
实例方法摘要折叠
-
# reset_counters (*counters) ⇒ 对象
使用 .count() 重置给定计数器 从数据库查询。
类方法详细信息
。 define_callbacks! (关联)⇒类
此方法是私有 API 的一部分。 您应尽可能避免使用此方法,因为它将来可能会被删除或更改。
添加负责更新计数器缓存字段的回调。
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 99 def self.define_callbacks!(关联) 名称 = 关联.名称 cache_column = 关联.counter_cache_column_name.to_sym 关联.inverse_class.点击 do |klass| klass.after_update do foreign_key = 关联.foreign_key if 发送(" #{ foreign_key } _previously_changed? ") 原始, Current = 发送(" #{ foreign_key } _previous_change ") 除非 原始.nil? 关联.klass.通过(persistence_context.for_child(关联.klass)) do |_class| _class.Decrement_counter(cache_column, 原始) end end if 记录 = __send__(名称) 除非 Current.nil? 记录[cache_column] = (记录[cache_column] || 0) + 1 记录.class.通过(记录.persistence_context) do |_class| _class.increment_counter(cache_column, Current) if 记录.持续存在? end end end end end klass.after_create do if 记录 = __send__(名称) 记录[cache_column] = (记录[cache_column] || 0) + 1 if 记录.持续存在? 记录.class.通过(记录.persistence_context) do |_class| _class.increment_counter(cache_column, 记录._id) end 记录.remove_change(cache_column) end end end klass.before_destroy do if 记录 = __send__(名称) 记录[cache_column] = (记录[cache_column] || 0) - 1 除非 记录.冻结? if 记录.持续存在? 记录.class.通过(记录.persistence_context) do |_class| _class.Decrement_counter(cache_column, 记录._id) end 记录.remove_change(cache_column) end end end end end |
实例方法详细信息
# reset_counters (*counters) ⇒对象
使用 .count() 重置给定计数器 从数据库查询。 如果计数器损坏或将新计数器添加到集合中,则此方法非常有用。
22 23 24 25 26 |
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 22 def reset_counters(*计数器) self.class.通过(persistence_context) do |_class| _class.reset_counters(self, *计数器) end end |