模块:Mongoid::Association::Referenced::CounterCache::ClassMethods

定义于:
lib/mongoid/association/referenced/counter_cache.rb

实例方法摘要折叠

实例方法详细信息

# decrement_counter (counter_name, ID ) ⇒对象

将与ID匹配的条目中的计数器名称减 1。 当启用 counter_cache 时,此方法用于关联回调

例子:

减少评论计数器

Post.decrement_counter(:comments_count, '50e0edd97c71c17ea9000001')

参数:

  • counter_name (符号)

    计数器缓存名称

  • id ( string )

    计数器将递减的对象的 ID。



84
85
86
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 84

def Decrement_counter(counter_name, id)
  update_counters(id, counter_name.to_sym => -1)
end

#increment_counter (counter_name, ID ) ⇒对象

将与ID匹配的条目中的计数器名称加 1。 当启用 counter_cache 时,此方法用于关联回调

例子:

增加评论计数器

Post.increment_counter(:comments_count, '50e0edd97c71c17ea9000001')

参数:

  • counter_name (符号)

    计数器缓存名称

  • id ( string )

    其计数器将递增的对象的 ID。



71
72
73
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 71

def increment_counter(counter_name, id)
  update_counters(id, counter_name.to_sym => 1)
end

# reset_counters ( ID , *counters) ⇒对象

使用 .count() 重置给定计数器 从数据库查询。 如果计数器损坏或将新计数器添加到集合中,则此方法非常有用。

例子:

重置给定计数器缓存

Post.reset_counters('50e0edd97c71c17ea9000001', :comments)

参数:

  • id ( string )

    将重置的对象的 ID。

  • *counters (符号... )

    要重置的一个或多个计数器缓存。



39
40
41
42
43
44
45
46
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 39

def reset_counters(id, *计数器)
  文档 = id.is_a?(文档) ? id : find(id)
  计数器. do |名称|
    role_association = 关系[名称]
    counter_name = role_association.inverse_association.counter_cache_column_name
    文档.update_attribute(counter_name, 文档.发送(名称).数数)
  end
end

# update_counters ( ID ,counters) ⇒对象

按值因子更新给定计数器。 它使用原子 $inc 命令。

例子:

将5添加到评论计数器,并从点赞删除2

counter.
Post.update_counters('50e0edd97c71c17ea9000001',
           :comments_count => 5, :likes_count => -2)

参数:

  • id ( string )

    要更新的对象的ID 。

  • 计数器 哈希


58
59
60
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 58

def update_counters(id, 计数器)
  WHERE(:_id => id).inc(计数器)
end