↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Remove N+1 queries in your Ruby on Rails app

The post explains the N+1 query problem as repeated database calls made while iterating over records and fetching the same associated data again and again. It shows how this slows pages down and uses a Rails example to illustrate the issue.

Reading notes
#

  • N+1 happens when a page loads a collection and then asks the database for the associated record for each item.
  • preload loads the main records and the associated records in two separate queries, but it does not support conditions on the associated table.
  • includes can choose between separate queries and a join, and it can be combined with references to force a LEFT OUTER JOIN.
  • eager_load works like includes with references and loads the data with one LEFT OUTER JOIN query.
  • Repeated aggregate calls with changing conditions can be replaced by grouping once and reading values from a hash.
  • Some multiple counts or sums can be merged into one SQL query with select and aliased expressions.
  • The Bullet gem helps detect N+1 queries during development by showing browser notifications when eager loading is needed or unnecessary.