Rails counter cache does not support conditions, so we often finding ourselves turning it off and manually incrementing and decrementing the
_count column. That’s fine.
However, without the
counter_counter directive in the
has_many, any calls to
.size will execute a
count(*) against the database instead of using the existing
_count column, which is definitely not what we expected.
I’ve searched through the history of the source code, and discovered this was the original behaviour, but PR 19042 made the change. While I can see how automatically
decrementing based only on the presence of the
_count column would be problematic, IMO there’s no downsize to
.size keeping the original (only checking the presence of the column).
I minor change would do it, I think, and avoid unexpected N+1
def count_records count = if owner.has_attribute?(reflection.counter_cache_column) owner.read_attribute(reflection.counter_cache_column).to_i else scope.count(:all) end