Read more

Don't name columns like counter_cache columns

Henning Koch
November 23, 2012Software engineer at makandra GmbH

ActiveRecord has a feature called counter caching Show archive.org snapshot where the containing record in a has_many relationship caches the number of its children. E.g. when you have House has_many :rooms, Rails can cache the number of rooms in House#rooms_count.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Mind that when a model has a column that looks to Rails like a counter-cache column, Rails will apply counter-cache logic to your model, even if you're not using counter caches.

E.g. you have a house with 12 rooms, but house.rooms_count is 0 (for whatever reason). Now house.rooms will always be empty because Rails thinks that there is no point in querying the database.

A solution is to use another naming convention (like total_rooms).

Posted by Henning Koch to makandra dev (2012-11-23 16:30)