# Counter\_cache and collections

**URL:** <https://www.ruby-forum.com/t/counter-cache-and-collections/124483>\
**Category:** Rails\
**Created:** [December 29, 2007, 3:37am UTC](https://www.ruby-forum.com/t/counter-cache-and-collections/124483 "2007-12-29T03:37:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![acampos](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/919ad9/32.png) [@acampos](https://www.ruby-forum.com/u/acampos)\
**Post date:** [December 29, 2007, 3:37am UTC](https://www.ruby-forum.com/t/counter-cache-and-collections/124483/1 "2007-12-29T03:37:07Z")

</div>

I’ve got a has\_many/belongs\_to association between two Rails models  
and I’m caching the child counter in the parent model via a  
counter\_cache. When adding a child to the parent via the ‘\<\<’ method  
of the parent, I was expecting the in-memory child counter in the  
parent to be updated, but it doesn’t appear as though it is. My  
controller code looks something like this:

def create  
@flag = Flag.new(params[:flag])  
@flag.user = authenticated\_user  
@listing = Listing.find(params[:listing\_id])  
@listing.flags \<\< @flag  
end

If I add a call to @listing.save after adding the child to the parent,  
the in-memory counter is updated, but I didn’t think the call to  
‘save’ was necessary. Am I doing something wrong or is this WAD?

---

<div class="post-metadata">

**Author:** ![acampos](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/919ad9/32.png) [@acampos](https://www.ruby-forum.com/u/acampos)\
**Post date:** [December 29, 2007, 8:56am UTC](https://www.ruby-forum.com/t/counter-cache-and-collections/124483/2 "2007-12-29T08:56:18Z")

</div>

I also tried

def create  
@listing = Listing.find(params[:listing\_id])  
@flag = listing.flags.create(params[:flag])  
@flag.user = authenticated\_user  
@flag.save  
end

but that didn’t do the trick either. The odd thing is when I try  
something similar in script/console, sometimes @listing.flags.size ==  
1 after the call to listing.flags.create and sometimes it remains at  
0. I should also mention that the flag model uses the acts\_as\_tree  
plugin in Rails 2.0, but does not use the counter\_cache option of the  
plugin.
