Skip to content

Instantly share code, notes, and snippets.

@cmoran92
cmoran92 / preload_counts.rb
Last active October 19, 2020 11:24 — forked from apauly/preload_counts.rb
Preload the count of associations similar to the familiar "preload"
#
# PreloadCounts
#
# Usage:
# collection = Post.limit(10).preload_counts(:users)
# collection.first.users.count # fires one query to fetch all counts
# collection[1].users.count # uses the cached value
# collection.last.users.count # uses the cached value
#
# Call `::PreloadCounts.enable!` inside of an initializer to enable preloading of association counts