Counter Cache Associations

Episode #78 by Teacher's Avatar David Kimura

Summary

When displaying a count of records, this will generate extra SQL Queries. Learn how to reduce the number of SQL queries called with counter caching the number of associated records.
rails model cache 3:54

Resources

Summary

# companies/index.html.erb
# Bad
<%= company.users.length %>

# Good
<%= company.users_count %>
<%= company.users.size %>

# user.rb
class User < ApplicationRecord
  belongs_to :company, counter_cache: true 
  # DEFAULT Column: users_count
  # belongs_to :company, counter_cache: :users_size 
end

# Terminal
rails g migration add_counter_cache_to_companies users_count:integer

# db/migrate/20170501010016_add_counter_cache_to_companies.rb
class AddCounterCacheToCompanies < ActiveRecord::Migration[5.0]
  def change
    add_column :companies, :users_count, :integer, default: 0
    Company.find_each { |company| Company.reset_counters(company.id, :users) }
  end
end