Detecting N+1 queries with Bullet
The Bullet gem is designed to help you increase your application's
performance by reducing the number of queries it makes. It will watch
your queries while you develop your application and notify you when
you should add eager loading (N+1 queries), when you're using eager
loading that isn't necessary and when you should use counter cache.
Related cards:
Strict Loading Associations can prevent n+1 queries
Rails 6.1 has a "strict loading" mode that forces the developer to preload any association they plan to use. Associations n...
PSA: Be super careful with complex `eager_load` or `includes` queries
TLDR
Using
.includes
or.eager_load
with 1-n associations is dangerous. Always use.preload
instead.
Consider the following ActiveRecord query:
BlogPost.eager_load(
:comments
:attachments,
).to_a
(Let's assume...
PostgreSQL: WITH Queries (Common Table Expressions)
PostgreSQL's Common Table Expressions (CTEs) can be used to extract sub-queries from bulky SQL statements into a temporary table to be referenced instead.
This is most useful to avoid ugly joins or sub-selects. CTEs can be used for SELECT
, `I...
Advice: Reduce scopes with joins to simple IN-queries
In theory you can take any scope and extend it with additional joins or conditions. We call this chaining scopes.
In practice chaining becomes problematic when scope chains grow more complex. In particular **having JOINs
in your scope will re...
Minidusen: Low-tech record filtering with LIKE queries
We have a new gem Minidusen which extracts Dusen's query parsing and LIKE
query functionality.
Minidusen can no longer index text in MySQL FULLTEXT columns, which was hardly used and didn't always help p...
Using rack-mini-profiler (with Unpoly)
Debugging performance issues in your Rails app can be a tough challenge.
To get more detailed insights consider using the rack-mini-profiler gem.
Setu...
Why preloading associations "randomly" uses joined tables or multiple queries
ActiveRecord gives you the :include
option to load records and their associations in a fixed number of queries. This is called preloading or eager loading associations. By preloading association...
Better performance insights with gem `rails_performance`
Even if you don't make any beginner mistakes like N+1 queries or missing DB indices, some requests can have bad performance. Without good performance metrics, you probably won't notice this until it's too late.
We investigated...
Howto use ActiveRecord preload with plain SQL inner joins
Like you know from "How to tell ActiveRecord how to preload associations (either JOINs or separate queries)", you can tell ActiveRecord explicitly if it should use a LEFT OUTER JOIN
or a separate query to preload associations....
Rails: Testing the number of database queries
There are a few tools to combat the dreaded n+1 queries. The bullet gem notifies you of missing eager-loading, and also if there is too much eager-loading. [strict_loadi...