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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)