Properly handle scoping with has_many :through. Fixes #14537.

See #14537