Skip to content

Instantly share code, notes, and snippets.

@johncip
Last active December 23, 2023 15:35
Show Gist options
  • Save johncip/17c496f04dcd032d594a785e2ad09824 to your computer and use it in GitHub Desktop.
Save johncip/17c496f04dcd032d594a785e2ad09824 to your computer and use it in GitHub Desktop.
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