3

I'm playing around with a fork of acts_as_taggable_on_steroids as a learning exercise. The version I'm looking at does some stuff I don't understand to calculate Tag counts. So I thought I'd do 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 accessed when I access tag.taggings.count but apparently not? Do I really have to access tag.tagging_counter_cache explicitly?

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

Same for size.

It's cool if that's the case but just wanted to check.

Julian H
  • 1,809
  • 17
  • 18

2 Answers2

2

Calling #size on the collection

>> tag.taggings.size

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

>> tag.taggings.count

will always force a sql call to get the latest count.

  • 1
    `#size` will give you size of the taggings collection. It is not always equal to counter cache value. For example, you could just build a new object in this collection which is not yet saved. In this case counter cache column will hold the number of saved objects only while `#size` will return the number of objects in collection including new ones. To get an exact value of counter cache use `tag[:taggings_count]`. `tag.taggings_count` should work as well but I am not sure. – skalee Jan 28 '11 at 17:13
0

Did you create the associated column in your migration? It needs someplace to store the cache.

Nick
  • 8,483
  • 10
  • 46
  • 65
  • Yep. Direct access to tagging_counter_cache returns the right value. Sorry I should've made that clear in the original qn. – Julian H Mar 28 '10 at 12:48