class User < ActiveRecord::Base
  has_many :items

  # screw n+1 problems from loading users, then fetching each user's item count
  # screw memory bloat from User.all.include(:items) and then user.items.size or count
  # screw custom sql, it's annoying to write, and you can't chain it
  # let arel + the db do the work!
  def with_item_counts
    column_names = columns.collect(&:name)
    select(column_names + ['count(items.id) as calculated_item_count']).joins('items').group(column_names)
  end

  def calculated_item_count
    super or raise 'use #with_item_counts scope if you want item counts'
  end
end