Rails 3: update counter_cache only if published

This is a difficult question.

I have a project with several types of content such as Article, Review, etc. Each type of content has comments; comments are polymorphic because they can belong to any type of content.

I want to put a common comment counter on all my content pages to show how many comments are there, and I used a cache counter to do this with. (Something like @ article.comments.count is more requests, and since I use the Ancestry gem for comments with a stream, the child’s comments are not counted in this number, but only in the root ones.)

The counting cache works fine and shows the exact number of comments, but, as always, one small catch. Comments are not always published immediately, only registered users can publish immediately, and these comments have the status: "2". Unregistered users get into the moderation queue; these comments have: status "1".

The problem is that the cache counter counts them anyway, so if you have four comments in moderation and one approved comment, the total is 5.

Is there a way to add an exception to the cache counter so that it does not increment if comment.status is not "2"? Similarly, when in the backend in the comments resource and setting this comment for publication (giving it status 2), is there a way (model, controller or otherwise) to make the cache counter for the polymorphic / type of content associated with it incremented?

comments.rb

# Comments has_many :comments, :as => :commentable, :dependent => :destroy accepts_nested_attributes_for :comments 

article.rb

 belongs_to :commentable, :polymorphic => TRUE, :touch => TRUE, :counter_cache => TRUE 
+6
source share
1 answer

Currently, I may think that you may have to provide your own cache counter columns in the model and increment / decrement as needed. i.e.

 active_comments_count pending_comments_count 

Then in your model you can call your update_comment_count method using callback .

His more efforts are on your side, but I'm sure this approach will work.

+5
source

Source: https://habr.com/ru/post/887087/


All Articles