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

Selecting outer leaf nodes #97

Closed
JanStevens opened this issue Apr 1, 2014 · 1 comment
Closed

Selecting outer leaf nodes #97

JanStevens opened this issue Apr 1, 2014 · 1 comment

Comments

@JanStevens
Copy link

Hello,

I'm missing a functionality for only selecting the outer leaf nodes of the tree without selecting nodes that act as a parent. The following method will fetch the outer leafs that are not a parent.

def all_leafs
    all = []
    self.children.each do |category|
      all << category if category.children.empty?
      root_children = category.all_leafs.flatten
      all << root_children unless root_children.empty?
    end
    # if there are no leafs then include itself
    all << self if self.children.empty?
    return all.flatten
end

I use it in combination with
(some tree model).map { |period| period.all_leafs.map(&:id).uniq }.flatten

Maybe this could be added (the concept) in a better way then recursively looping through the tree. Or is there a method that already returns the outer leaf nodes?

@mceachen
Copy link
Collaborator

Sorry for the delay.

It turns out that .leaves is already available on your model! See https://github.com/mceachen/closure_tree#class-methods

It looks like you wanted all the IDs for your leaf nodes. That's just:

Tag.leaves.pluck(:id)

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

No branches or pull requests

2 participants