avoiding n+1 errors in rails apps
TRANSCRIPT
N+1 Errors
Hi! I’m Esther.I’m a software developer at MarryMapp
and a recent Dev Bootcamp grad(and I <3 Ruby)
estherleytush.com
This talk was made with newbies in mind.
What are n+1 errors, in a nutshell?
Here’s what happens...
Database is queried for
parent record
App needs info about child
records
Database is queried once
per child record
Products and users:
×An product index page asks for info about some products...
×Then needs to load info about the product creator…
×...querying the database for each creator.
So, why is this a
problem?
What if you’re making 100s, 1000s, 10000(...)’s requests? What if your server is far away?
If it takes 1ms to make 1 request, 2ms for 2... Those numbers compound painfully.
Because it slows pages down.
What would be faster?
Making 1 query with 100 results
instead of 100 queries with 1 result
each.
Let’s go see it!
Your Rails tools
:preload:includes:eager_loadPre-make aggregate database queries for the resource you need
Post.preload(:user)
AssociationsPre-make an association for the resource you’ll need in order to preload it
has_one :latest_post, -> { order(created_at: :desc).limit(1) }, class_name: "Post"
“Try the Bullet gem, too:
It informs you of n+1 errors via excellent logging capability.
Thanks!
Any questions?estherleytush.comGithub: mindplace