Ever since I created my own blogging engine, I have been struggling with enormous amounts of comment spam. I don’t have time to manually delete the spam, so I installed a spam checking service to figure out if the comments are spam.
My post model has a counter_cache column used to keep track on how many comments each post has so I have that information handy when needed and don’t need to ask the database each time. Using rails, you define the coulumn in a belongs_to associative declaration and the counter is updated automatically in the parent model (google counter_cache rails if you want to know about it). The only problem is that the counter_cache column in rails does not support conditional tracking. I found the same discussion on this guy Douglas’ website and a couple of work-arounds can be found there.
What I ended up doing was almost the same but I didn’t created a second column since I only need to know how many non-spam comments I have. I just disabled the automatic counter cache and decided it’s better to just keep track manually. My comment model now looks like this:
belongs_to :post # removed counter_cache => true named_scope :approved, :conditions => {:approved => true} after_save :update_comments_count after_destroy :update_comments_count def update_comments_count self.post.update_attributes :comments_count => self.post.comments.approved.count end
Thanks, this is a great example, very useful!