Hacker News new | ask | show | jobs
by nathan_long 2655 days ago
> Perhaps you don't want everything eager loaded, but you want an exception to be raised if you try to access an associated record that hasn't been preloaded.

Yes, exactly.

> When I need to load/use them along with many parent records, it seems pretty obvious that I'll want to include those associations (eagerly loaded) in my AR query to avoid N+1 queries as you mentioned. Then again, maybe I've just spent too long taking those assumptions for granted where newer devs might not.

You know that and I do too, but legacy Rails apps tend to be full of N+1 queries in my experience, and it's a major cause of slowdowns.

1 comments

Looks like the bullet gem does what you want.

https://semaphoreci.com/blog/2017/08/09/faster-rails-elimina...

https://github.com/flyerhzm/bullet

EDIT: It looks like this was already mentioned in another thread. I guess I don't understand the issue if that doesn't solve your problem.

The bullet gem has helped me solve this problem in specific applications before, yes.

My higher-level problem is that having lazy-loading on by default allows N+1 queries to creep in to a code base and you need a third-party gem to find them. I've had to spend significant time finding and fixing this after joining teams with large legacy apps.

"Disable lazy loading globally" should be an ActiveRecord setting and it should be on by default IMO; people who need lazy loading should have to turn it on per query, something like `query.allow_lazy_loading(post: :author)`. I suspect that a very small fraction of queries would use this, since many apps don't do server side rendering, many who do SSR don't use Russian doll caching, and even those who do both still execute many queries that should prefetch all the associations they use.