Filtering by Association Count in Complex Models in Rails

Filtering complex associations in Rails can get tricky: built-in methods like where.associated don’t always provide efficient results. Here’s how I used a SQL subquery inside Rails scopes to make a slow page fast again.