Ruby on Rails — What is counter_cache ?

Albert Hu
Albert’s Coding Adventures
1 min readNov 21, 2017

Recently, I wanted to verify something in the Magoosh code base:

do we still increment users.answers_count ?

I did a cmd-shift-f in my editor and looked for instances of a .answers_count code snippet and couldn’t find anything related to Users.. it turns out, the Answer model has a belongs_to association with an interesting option:

According to the Rails documentation, counter_cache gives you the ability to automatically increment and cache the count (*surprise*) of an association on the parent model in two steps:

  1. add a counter cache on the belonging model, in this case answer.rb
  2. add a column named like answers_count on the associated model, in this case user.rb

Indeed, when I checked again, User and Answer were set up as such:

Now I’m happy I understand how all the <model_name>s_count's are incremented all around our code! Try this out for yourself if you want to avoid doing something like:

@user.answers.count

and forcing rails to run a query every time, just to calculate how many answers the user has, and instead, have the count right at your fingertips:

@user.answers_count

--

--