Access cache ruby ​​counter

I play with the fork act_as_taggable_on_steroids as a training exercise. The version I'm looking at does some things that I don’t understand in order to count the number of tags. So I thought I would make a version using PORC (Plain Old Rails Counters):

class Tagging < ActiveRecord::Base #:nodoc:
  belongs_to :tag, :counter_cache => "tagging_counter_cache"
...

I thought tagging_counter_cache was transparently available when I access tag.taggings.count, but apparently not? Do I really have to explicitly access tag.tagging_counter_cache?

>> tag.taggings.count
  SQL (0.7ms)   SELECT count(*) AS count_all FROM `taggings` WHERE (`taggings`.tag_id = 16) 

Same for size.

This is great if this is the case, but just need to check.

+3
source share
2 answers

Call #size in a collection

>> tag.taggings.size

will return the value in the counter cache. Call #count

>> tag.taggings.count

will always make sql call get the last count.

+2

? .

0

Source: https://habr.com/ru/post/1738318/


All Articles