Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Active Record eager loading strategies

N+1 query problem

  • ORMs make it easy to a query per loop iteration, which we want to avoid

eager_load

  • single query (left outer join)
  • can reference the other table's columns in where

preload

  • a few queries (one per table)
  • typically faster

includes

  • acts like preload by default
  • falls back on eager_load if you reference the associated tables

joins

  • inner join
  • precise; allows you to avoid loading extra data
  • can use aliases to add new methods to left table's records

Other AR optimizations

  • queries can be built without being fired (calling e.g. all, first, count, or each does that)
  • results of recent queries are cached
  • these don't help with the N+1 problem

Tips

  • index on foreign keys
  • benchmark with a remote db if that's what prod uses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.