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

reason for with_ancestor method using map #408

Closed
ggLee6352 opened this issue Sep 14, 2022 · 2 comments
Closed

reason for with_ancestor method using map #408

ggLee6352 opened this issue Sep 14, 2022 · 2 comments

Comments

@ggLee6352
Copy link

ggLee6352 commented Sep 14, 2022

# lib/closure_tree/finders.rb

def with_ancestor(*ancestors)
  ancestor_ids = ancestors.map { |ea| ea.is_a?(ActiveRecord::Base) ? ea._ct_id : ea }
  scope = ancestor_ids.blank? ? all : joins(:ancestor_hierarchies).
    where("#{_ct.hierarchy_table_name}.ancestor_id" => ancestor_ids).
    where("#{_ct.hierarchy_table_name}.generations > 0").
    readonly(false)
  _ct.scope_with_order(scope)
end
def with_ancestor(*ancestors)
  scope = ancestor_ids.blank? ? all : joins(:ancestor_hierarchies).
    where("#{_ct.hierarchy_table_name}.ancestor_id" => ancestor_ids).
    where("#{_ct.hierarchy_table_name}.generations > 0").
    readonly(false)
  _ct.scope_with_order(scope)
end

seem to be the same

@ggLee6352 ggLee6352 changed the title reason for with_ancestor method using map? reason for with_ancestor method using map Sep 14, 2022
@mhazim2
Copy link

mhazim2 commented Oct 14, 2022

@ggLee6352 map was used to process *ancestors arguments if given any to filter out the results that is descendants of given ancestors. If no argument passed, then will use all scope instead

Model.with_ancestor(1, 2).to_sql
=> SELECT "models".* FROM "models" INNER JOIN "model_hierarchies" ON "model_hierarchies"."descendant_id" = "models"."id" WHERE "model_hierarchies"."ancestor_id" IN (1, 2) AND (model_hierarchies.generations > 0)

Model.with_ancestor([1, 2]).to_sql
=> SELECT "models".* FROM "models" INNER JOIN "model_hierarchies" ON "model_hierarchies"."descendant_id" = "models"."id" WHERE "model_hierarchies"."ancestor_id" IN (1, 2) AND (model_hierarchies.generations > 0)

Model.with_ancestor.to_sql
=> SELECT "models".* FROM "models"

Your example by removing ancestors.map { ... } will raise error caused ancestor_ids was not defined since with_ancestor method was a class method not instance method (with_ancestor defined under ClassMethods module)

@kbrock
Copy link
Contributor

kbrock commented Mar 13, 2023

Is this still an issue? Can it be closed?

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

3 participants