# Problems with counter cache on trunk (rev: 5788)

**URL:** <https://www.ruby-forum.com/t/problems-with-counter-cache-on-trunk-rev-5788/80832>\
**Category:** Rails\
**Created:** [December 31, 2006, 12:40am UTC](https://www.ruby-forum.com/t/problems-with-counter-cache-on-trunk-rev-5788/80832 "2006-12-31T00:40:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Abdur-Rahman](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/91b2a8/32.png) [@Abdur-Rahman](https://www.ruby-forum.com/u/Abdur-Rahman)\
**Post date:** [December 31, 2006, 12:40am UTC](https://www.ruby-forum.com/t/problems-with-counter-cache-on-trunk-rev-5788/80832/1 "2006-12-31T00:40:46Z")

</div>

Hi guys,

I have a problem with counter cache on the rails trunk version. I have  
the following test case (tried to post on core mailing list but looks  
like it isn’t accepting my mail):

doc = Document.new  
assert doc.bookmarks.create()  
assert doc.save!  
assert doc.reload  
assert\_equal 1, doc.bookmarks\_count

But doc.save! sets the bookmarks\_count column on document to 0 (after  
it has been raised by bookmarks.create)

the following queries can be found in log:

1. SELECT \* FROM documents WHERE (documents.id = 1)
2. UPDATE documents SET bookmarks\_count = bookmarks\_count + 1 WHERE (id  
= 1)
3. COMMIT
4. BEGIN
5. SELECT \* FROM bookmarks WHERE (bookmarks.bookmarkable\_id = 1 AND  
bookmarks.bookmarkable\_type = ‘Document’)
6. UPDATE documents SET `content` = NULL, `bookmarks_count` = 0, `name`  
= NULL WHERE id = 1
7. COMMIT

quite frustrating… :S

My models:

– Document.rb:  
class Document \< ActiveRecord::Base  
has\_many :bookmarks, :as =\> :bookmarkable, :dependent =\> :destroy  
end

– Bookmark.rb:  
class Bookmark \< ActiveRecord::Base

# associations

belongs\_to :bookmarkable, :polymorphic =\> true, :counter\_cache =\>  
“bookmarks\_count”  
end

Thnx,

Abdul

---

<div class="post-metadata">

**Author:** ![Abdur-Rahman](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/91b2a8/32.png) [@Abdur-Rahman](https://www.ruby-forum.com/u/Abdur-Rahman)\
**Post date:** [March 5, 2007, 7:57pm UTC](https://www.ruby-forum.com/t/problems-with-counter-cache-on-trunk-rev-5788/80832/2 "2007-03-05T19:57:35Z")

</div>

Same deal here, although it is far classier to present the bug as a  
failed test. The memory version of Document isn’t updating on the  
create, although the increment SQL was geerated. Thus, the save of  
Doc overwrites the properly updated database info so that the reload  
has the old, pre-creation, value of the counter cache.

This really used to work for me – don’t know where it went bad.

I’m working on a scratch 1.2.2 install.
