ruby 20 lines · 2 tabs

Counter cache for association counts

Alex Kumar Jan 2026
2 tabs
class AddCommentsCountToPosts < ActiveRecord::Migration[6.1]
  def up
    add_column :posts, :comments_count, :integer, default: 0, null: false

    # Populate existing counts
    Post.find_each do |post|
      Post.reset_counters(post.id, :comments)
    end
  end

  def down
    remove_column :posts, :comments_count
  end
end
2 files · ruby Explain with highlit

Computing counts on associations can be expensive when done repeatedly—post.comments.count executes a SELECT COUNT(*) query every time. Counter caches solve this by maintaining a denormalized count column on the parent model that increments/decrements automatically when children are created or destroyed. This trades a small amount of write overhead (updating the counter) for massive read performance gains. I add counter_cache: true to the belongs_to association and create a migration to add the *_count column with a default of 0. For existing data, I use reset_counters to populate initial values. Counter caches work best for read-heavy associations where counts are displayed frequently, like comment counts or like counts on posts.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Counter cache for association counts — share card
Link copied