Code Explainers

Code explainers tagged #counter-cache

ruby
class Post < ApplicationRecord
  belongs_to :author, counter_cache: false
  has_many :comments, dependent: :destroy
end

A custom counter cache in Rails

counter-cache callbacks associations
Intermediate 7 steps
ruby
namespace :counter_cache do
  desc "Recalculate comments_count for posts after a backfill"
  task warm_post_comments: :environment do
    scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))

Backfilling counter caches in a Rake task in Rails

counter-cache batching rake-tasks
Intermediate 6 steps
ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true, counter_cache: true
  belongs_to :author, class_name: "User"
 

How polymorphic comments work in Rails

polymorphic-association concerns counter-cache
Intermediate 8 steps
ruby
class CreateCommentsWithCounterCache < ActiveRecord::Migration[7.1]
  def change
    create_table :posts do |t|
      t.string :title, null: false

How counter caches work in Rails

counter-cache migrations associations
Intermediate 6 steps