This project is archived and is in readonly mode.

#2907 open
Szymon Nowak

Custom counter_cache is not used when using collection.size method

Reported by Szymon Nowak | July 14th, 2009 @ 12:02 AM | in 2.3.10

While writing a patch for belongs_to association, I've encountered the following issue:

class Author < AR::Base
  has_many :posts
class Post < AR::Base
  belongs_to :author, :counter_cache => "custom_posts_count"

a = Author.create p = Post.create = a # updates counter on Author, but doesn't save post object

Author.find(, "custom_posts_count" # 1; uses counter cache Author.find( # 0; uses SQL count

In the second example SQL count is used because in HasManyAssociation#count_records method, there's check if there's cache counter:

def has_cached_counter?
def cached_counter_attribute_name
which fails in this case. It simply uses name of the reflection, not the value of :counter_cache option on belongs_to association, or table name as described in docs.

Not sure if there's an easy solution for this if counter cache column name is defined on belongs_to association and not has_many.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

Referenced by