Backport of fix for issue #7630

This backport fixes issue #7630, a bug in `has_many_through` counter caches, in Rails 3.2 (the original commit was ea77ec2).