Register now and start sharing your code snippets.
-->

How to update the ActiveRecord counter_cache magic column

SQL posted 2 months ago by christian

You can use the model.update_counters method to update the counter_cache column. But if you have a million rows it be very fast.

So for large tables it’s best to do it with a query such as this:

   1  update categories, (select 
   2                        id as category_id, ifnull(count, 0) as count
   3                      from categories left join 
   4                        (select category_id, count(id) as count from products group by category_id) as count_table 
   5                      on 
   6                        categories.id = count_table.category_id) as count_table
   7  set 
   8    categories.products_count = count_table.count
   9  where
  10    categories.id = count_table.category_id

This query updates the count for all rows.

The code needs to be modified for your database design.

Tagged update, counter_cache, sql, rails, active_record