📎 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.
preloadloads the main records and the associated records in two separate queries, but it does not support conditions on the associated table.includescan choose between separate queries and a join, and it can be combined withreferencesto force aLEFT OUTER JOIN.eager_loadworks likeincludeswithreferencesand loads the data with oneLEFT OUTER JOINquery.- 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
selectand aliased expressions. - The Bullet gem helps detect N+1 queries during development by showing browser notifications when eager loading is needed or unnecessary.
