Counter_cache won't increment

I’m having an odd problem. I’ve pinpointed what’s causing it, but it’s
not making any sense.

class Discussion < ActiveRecord::Base
has_many :posts, :dependent => :destroy

def bump
update_attribute(:bumped_on, Time.now)
end
end

class Post < ActiveRecord::Base
belongs_to :discussion, :counter_cache => true

after_create :bump_discussion

def bump_discussion
discussion.bump
end
end

Now I can do something obvious like
post = Post.new
post.discussion = Discussion.find(:first)
post.save

But this won’t increment posts_count in the discussions table. HOWEVER,
if I remove the bump_discussion method then posts_count DOES get
updated. This doesn’t really make any sense. My guess is that updating
the row one way is overriding the other update.

Furthermore, calling Post.destroy_all seems to show that things would be
working, but obviously MySQL chokes since I am trying to have it
decrement 0 by 1, and the column is an unsigned integer (no negative
numbers.)

What’s up with this?

Eleo wrote:

Now I can do something obvious like
post = Post.new
post.discussion = Discussion.find(:first)
post.save

But this won’t increment posts_count in the discussions table. HOWEVER,
if I remove the bump_discussion method then posts_count DOES get
updated. This doesn’t really make any sense. My guess is that updating
the row one way is overriding the other update.

Currently counter_cache fields are not excluded from being updated
when a save is done, so the updated count, written directly to the DB,
is getting overwritten by the old count in the Discussion object.

The most simple solution is to rewrite bump as

def bump
update_all “bumped_on = #{self.class.sanitize(Time.now)}”, “id =
#{id}”
end


We develop, watch us RoR, in numbers too big to ignore.

Sigh, snags.

Thanks for answering. Your solution worked fine.