ruby-on-railsrubyruby-on-rails-3associationscounter-cache

How to set a counter cache value to a given one?


I am using Ruby on Rails 3.2.2 and I would like to set a counter cache value to a "custom" one. That is, at this time (in my migration file) I am trying to use the following code:

def up
  add_column :articles, :comments_count, :integer, :default => 0

  Article.reset_column_information

  Article.find_each do |article|
    # Note: The following code doesn't work (when I migrate the database it   
    # raises the error "comments_count is marked as readonly").
    Article.update_column(:comments_count, article.custom_comments.count)
  end
end

In other words, I would like to set the :comments_count value (a counter cache database table column) to a custom value (in my case that value is article.custom_comments.count - note: the custom_comments is not an ActiveRecord Association but a method stated in the Article model class; it returns an integer value as well) that is not related to a has_many associations.

Maybe, I could / should use something like

Article.reset_column_information

Article.find_each do |article|
  Article.reset_counters(article.id, ...)
end

but it seems that the reset_counters method cannot work without has_many associations.

How can I set the :comments_count counter cache value to a given value that is related to a "custom association"?


Solution

  • You describe comments_count as a counter cache, yet a counter cache is strictly defined as the number of associated records in a has_many relationship, which you say this isn't.

    If the only way to get the value you want is via method on Article, then you're going to have to iterate over all your Article objects and update each one.

    Article.find_each do |article|
      article.update_attribute(:comments_count, article.custom_comments.count)
    end
    

    This is pretty inefficient, since it's loading and saving every object. If the definition of custom_comments (which you don't actually explain) is something you can express in SQL, it would undoubtedly be faster to do this update in the database. Which might look something like this:

    CREATE TEMP TABLE custom_comment_counts_temp AS
      SELECT articles.id as id, count(comments.id) as custom_comments 
        FROM articles 
        LEFT JOIN comments ON articles.id = comments.article_id
        WHERE <whatever condition indicates custom comments>
        GROUP BY articles.id;
    
    CREATE INDEX ON custom_comments_counts_temp(id);
    
    UPDATE articles SET comments_count = (SELECT custom_comments FROM custom_comment_counts_temp WHERE custom_comment_counts_temp.id = articles.id);
    
    DROP TABLE custom_comment_counts_temp;
    

    (this assumes postgresql - if you're using mySQL or some other database, it may look different. If you're not using a relational database at all, it may not be possible)

    Additionally, since it's not a counter cache according to Rails' fairly narrow definition, you'll need to write some callbacks that keep these values updated - probably an after_save callback on comment, something like this:

    comment.rb:

    after_save :set_article_custom_comments
    
    
    def set_article_custom_comments
      a = self.article
      a.update_attribute(:comments_count, a.custom_comments.count)
    end