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
end
class Post < AR::Base
  belongs_to :author, :counter_cache => "custom_posts_count"
end


a = Author.create p = Post.create


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


Author.find(a.id).send(:read_attribute, "custom_posts_count" # 1; uses counter cache Author.find(a.id).posts.size # 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?
  @owner.attribute_present?(cached_counter_attribute_name)
end
def cached_counter_attribute_name
  "#{@reflection.name}_count"
end
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="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages