backport of fix for issue #7630
Merge pull request #9278 from matthewrobertson/backport-hmt-counter-cache-bug

Backport of #8400 to fix for issue #7630, a bug in has_many :through counter caches.