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