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
, oreach
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