alphagov/transition — pull request #301 by rgarner (2014-06-03 13:40:17+00:00)
Title: Eager load mapping relations

What started out as a one-liner turned into something a little larger.

The ["performance spike"](https://www.pivotaltracker.com/story/show/71235350), such as it is, turns out to be a great deal quicker to do by addressing problems as they are encountered and while context is fresh rather than documenting the problem and creating a story for it (since the context is loaded, it's simpler to deal with it now rather than go through the intermediate story steps). Apologies if this makes it hard to track what's been done; I can always go back and create a bunch of already-complete one-point stories after the fact :wink:

There is one commit per performance improvement. Improvements have been measured using [`rack-mini-profiler`](https://github.com/MiniProfiler/rack-mini-profiler) and N+1 queries were identified by me, then [Bullet](https://github.com/flyerhzm/bullet), in that order (Bullet is better than me at spotting them, it turns out). They've taken the form of:

* Avoiding N+1 queries with eager loading
* Optimising query plans by switching to columns with indices
* Caching expensive things that were being evaluated per-row within the context of the whole request
* Changing views so that hidden query triggers are avoided, sometimes in association with eager loading

What's been improved in this PR:

* The showing of sites
* The listing and filtering of mappings
* Tags (optimising general-case methods like AATO's `Model#tag_counts_on`, which has a net benefit for three different areas)
* Getting data access out of helpers

What's out of scope:

* Hits/Analytics. This is a bigger issue and this PR was getting big enough already. I intend to move straight on, though.