/dev/random

Database N+1 Queries

Was recently reminded to always be on the lookout for potential n+1 query pitfalls. Take a look at the code before:

index = (string.size-1).downto(0).find {|i| Foo::Model.find_by(bar: string[0..i])}
index ? string[0..index] : nil

Versus the after:

candidates = string.length.times.map {|i| string[0..i]}
Foo::Model.where(bar: candidates).order('length(bar) desc').take&.bar

Much nicer doing 1 trip to the db with the query selecting and sorting instead of searching candidates one by one, up to string.length times.