Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid N + 1 queries #140

Closed
lucasas opened this issue Jun 13, 2013 · 8 comments
Closed

Avoid N + 1 queries #140

lucasas opened this issue Jun 13, 2013 · 8 comments

Comments

@lucasas
Copy link

lucasas commented Jun 13, 2013

Hi guys,

First of all, thank you for the great work with this gem.

I have some performance issues here, because N + 1 queries using ancestry.

I have a model:

class Category < ActiveRecord::Base
   acts_as_tree
end

And I want to load all root categories loading all children of each one.

roots = Category.roots
roots.each { |r| r.children }

I want to execute only 2 queries here. I was looking for this into source code, but I didnt find it. Is there any plan to solve this performance issue?

Thank you.

@holstvoogd
Copy link

This is not a ancestry issue, but with your code. You iterate over an array build from a query, so yes, you'll get N+1 queries where N is the size of that array.
You could try something like:

Category.where(:ancestry => Catergory.roots.pluck(:id)).all

# or if you have depth caching on:
Category.where(:ancestry_depth_cache => 1).all

@lucasas
Copy link
Author

lucasas commented Jun 14, 2013

I understood @holstvoogd, but it is not so object oriented, right?

@holstvoogd
Copy link

sure, but that is how ActiveRecord works. the .each call causes the first query to execute and then you have a simple array, so N queries.

@lucasas
Copy link
Author

lucasas commented Jun 17, 2013

But when I use includes Active Record executes only 2 queries instead of N + 1. There is some plan to implement or have something equal to includes method? Thanks

@mjc
Copy link
Contributor

mjc commented Dec 24, 2013

If .includes() worked, rendering a collection wouldn't result in N+1 queries either.

@alexanderadam
Copy link

Sorry for reviving this issue but is there nowadays some integration for includes / eager_load / preload in ancestry?

@kbrock
Copy link
Collaborator

kbrock commented Jul 11, 2019

@alexanderadam I'm sorry to say that no. at this time there is no includes support

@alexanderadam
Copy link

What a pity. Thank you for responding so fast.
Could #440 stay open or is it possible to reopen this issue here so that everybody can see that this isn't solved yet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants