Resetting counter cache value in your Rails models


Instead of counting the associated records in the database every time, ActiveRecord’s counter caching feature allows storing the counter and updating it every time an associated object is created or removed.

In Rails apps you can set your counter cache option for association with simple code.

This means, what you need to have authors_count integer column in your model related table.

Adding counter cache to your model

class Campaign
  belongs_to :author, counter_cache: true
end

Let’s generate a database migration.

$ rails generate migration AddCampaignsCountToAuthors campaigns_count:integer
      invoke  active_record
      create    db/migrate/20190618093257_add_campaigns_count_to_authors.rb
$ rake db:migrate
== 20190618093257 AddCampaignsCountToAuthors: migrating ======================
-- add_column(:authors, :campaigns_count, :integer)
  -> 0.0016s
== 20190618093257 AddCampaignsCountToAuthors: migrated (0.0017s) =============

Populating the counter cache

Usually you already have some code / data, and all what you need - recount numbers in database. You can do that with simple rake task.

namespace :caching do
  desc "Update counter cache"
  task gencache: :environment do
    Author.find_each do |author|
      Author.reset_counters(author.id, :campaigns)
    end
  end
end