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

Getting common ancestors / merging ancestors #479

Open
mbajur opened this issue Jan 16, 2024 · 1 comment
Open

Getting common ancestors / merging ancestors #479

mbajur opened this issue Jan 16, 2024 · 1 comment
Labels

Comments

@mbajur
Copy link

mbajur commented Jan 16, 2024

Hello!

I have a case in which i have multiple sets of self_and_ancestors results. The amount of these sets depends on the variable which makes it unpredictable and N+1 prone therefore i was looking for some ways of simplifying that with one query. Let's say my code looks as follows:

taxons = []

product.taxons.each do |taxon|
  taxon.self_and_ancestors.each { |t| taxons << t }
end

Which obviously produces new query for each self_and_ancestors call. So if there are 100 product.taxons, 100 queries will be produced.

I was experimenting with doing that with merge:

collection = Spree::Taxon.all
product.taxons.each do |taxon|
  collection.merge!(taxon.self_and_ancestors)
end

which indeed produced one single query but it operates on lft and rgt columns and i have no idea if that's proper way of handling that and/or this produced sql query is valid. In fact, it merged where statements for all of the self_and_ancestors calls.

For your convenience, i prepared an example for you. Let's say product.taxons returns two taxons. Here are the sql queries produced for each one of them:

product.taxons.first.self_and_ancestors.to_sql
# => SELECT "spree_taxons".* FROM "spree_taxons" WHERE "spree_taxons"."lft" <= 1 AND "spree_taxons"."rgt" >= 232 ORDER BY lft

product.taxons.last.self_and_ancestors.to_sql
# => SELECT "spree_taxons".* FROM "spree_taxons" WHERE "spree_taxons"."lft" <= 201 AND "spree_taxons"."rgt" >= 202 ORDER BY lft                                                                                     

And here is the result of merging them:

collection = Spree::Taxon.all
product.taxons.each do |taxon|
  collection.merge!(taxon.self_and_ancestors)
end
collection.to_sql
# => SELECT "spree_taxons".* FROM "spree_taxons" WHERE "spree_taxons"."lft" <= 201 AND "spree_taxons"."rgt" >= 202 ORDER BY lft

Does that look valid to you? Is that how i should approach that?

Copy link

stale bot commented Mar 13, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Mar 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant