Problems with counter cache on trunk (rev: 5788)

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 =
assert doc.bookmarks.create()
assert doc.reload
assert_equal 1, doc.bookmarks_count

But! 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 ( = 1)
  2. UPDATE documents SET bookmarks_count = bookmarks_count + 1 WHERE (id
    = 1)
  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

quite frustrating… :S

My models:

– Document.rb:
class Document < ActiveRecord::Base
has_many :bookmarks, :as => :bookmarkable, :dependent => :destroy

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


belongs_to :bookmarkable, :polymorphic => true, :counter_cache =>



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.