May 2025
Intermediate to advanced
270 pages
6h 55m
English
Let’s start with one of the easiest and cleanest Rails tricks you have at your disposal: counter_cache. This feature has been in Ruby on Rails since Rails 0.9.0 (!) in 2004. The use case is simple in the context of a web application; often, the number of objects associated with a particular model needs to be counted. For example, in the API customers#index endpoint, the application renders the number of rentals each customer has done in the past. Try it out by calling /api/v1/customers from your browser and checking the log. You would get the same by running on the Rails console: Customer.all.map { |c| c.rentals.count }.
| | Started GET "/api/v1/customers" for ::1 at 2025-02-17 15:58:57 -0500 |
| | Processing by Api::V1::CustomersController#index ... |
Read now
Unlock full access