Don't name columns like counter_cache columns in Rails pre v4.2.4

Updated . Posted . Visible to the public. Deprecated.

This has been resolved since Rails v4.2.4., have a look this commit and the linked issues.

< Rails v4.2.4

ActiveRecord has a feature called counter caching Show 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.

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).

>= Rails v4.2.4

#has_cached_counter? enforces that the counter_cache option must be given on either the owner or inverse since this commit Show snapshot , whereas it only looked at the presence of the attribute before.

Henning Koch
Last edit
Felix Eschey
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2012-11-23 15:30)