Counter Cache to Optimize Queries
Rails has a neat feature to cache counters1 for associations.
belongs_to :author, counter_cache: true
- Need to add a column
books_count
for that to work. - Or specify a specific column instead:
belongs_to :author, counter_cache: :count_of_books