June 2024
Intermediate to advanced
456 pages
11h 34m
English
The Active Record counter cache improves slow COUNT() queries by replacing them with a pre-computed count. They work by keeping a running tally of the count, stored in an integer column that’s fast to access. As you will see elsewhere, the trade-off here is space consumption for improved access performance.
In Rideshare, imagine that you’d like to count the number of trips a Driver has performed. This query could be run in high volume, so you’d like to make it efficient. The code might look like this:
| | Driver.first.trips.count |
This code uses the .count Active Record method, which always generates a SQL COUNT() query. Before adding a counter cache column, one improvement would be to replace .count ...
Read now
Unlock full access