Hi. I have a problem with counters in Rails. The situation looks like this: -3 simple models class Forum < ActiveRecord::Base has_many :posts end class Topic < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :topic, :counter_cache => true belongs_to :forum, :counter_cache => true end - In migrations i have declared t.column :posts_count, :integer, :default => 0 for Forum and Topic - Now a simple action def some_action @post = Post.new(params[:id]) @forum.posts << @post # The @forums.posts_count is up by 1 @topic.posts << @post # The @topic.posts_count is _not_ up by 1 end Both, the forum_id and topic_id are set correctly in @post, it saves into the database and everything else is dandy. But why oh why doesn't the @topic.posts_count increment ? (oh, obviously if I change the order of the two crucial lines the effect will be the same - the instance in the second line won't get the posts_count incremented) Could anyone come up with a solution ? (apart from making the counters 'by hand')
on 2007-05-14 18:08
on 2007-05-14 21:06
> @forum.posts << @post # The @forums.posts_count is up by 1 > @topic.posts << @post # The @topic.posts_count is _not_ up by 1 Just a guess, but I think it only updates on the first attempt because increment_counter is only called if the it's a new record. So, for the first one, it's a new record, but for the second it's existing - so no update. Do the counters update correctly on save?
on 2007-05-14 21:15
The fundamental problem is that in order to increment the counter when an existing record was associated, an extra query would be required to determine whether that record was already included in the count. At that point the performance gain of the counter is lost since you might as well just query for the COUNT again. Then there's the whole issue of deleting posts. I'm assuming the counter would not decrement unless you call @forum.posts.delete(id). In my experience the counter caches are scarily brittle. If the given model is ONLY created through the association then they can be manageable and offer a slight performance benefit, but if you have the proper index, a COUNT(*) query is extremely fast. On May 14, 1:06 pm, David Coleman <rails-mailing-l...@andreas-s.net>
on 2007-05-15 00:44
> > Do the counters update correctly on save? Very much inline with what dasil said, the rails counters are very brittle, but they are typically per-object caches, so this should be alright. However, to be sure, I recommend in a unit test, trying out. assert_equal @forum.posts.count, 1 assert_equal @topic.posts.count, 1 Your assertion may very well fail, but you should check log/test.log and examine what SQL queries Rails dispatched if any.