3
0 Comments

Complex preloading in Rails with custom scopes

So if you're ever faced the need to define custom associations (e.g. has_many association where the IDs are stored as an array on the parent model) then doing proper preloading - to avoid N+1 queries - becomes a bit of a pain.

The Rails preload and eager_load functionalities are made for standard associations and are not really customisable.

The blog post below presents an alternative way to defining custom scopes when your preloading logic doesn't entirely rely on Active Record associations.

https://www.keypup.io/blog/complex-preloading-strategies-in-rails-using-custom-active-record-scopes

If you have come across this problem, I'd curious to know if you've found other solutions to address it.

on February 23, 2021