RubyFlow The Ruby and Rails community linklog

Recalculate counter cache columns in Rails

Rails has this great feature called counter_cache. When you have a has_many/belongs_to relationship between two models, it basically lets you say that you want to save the number of associated objects on the has_many side. So if you have Post has many Comments, you can do post#size and no SQL query is executed, Rails simply just looks at the comments_count field of the post.

Sometimes that field gets out of sync though, and if that happens, here is how to recalculate it!

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in