Eleo wrote:
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.
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