user984621
user984621

Reputation: 48483

Awesome nested set - how can I get a statement of any subtree?

I am a newbie and I am playing with this gem. I have in database a tree structure. But now I am struggling with a way, how to get a statement of items for example on the first level... or the count items on the first or second level...

Could anyone help me please with this problem? I found at GitHub this loop for a statement of items:

Category.each_with_level(Category.root.self_and_descendants) do |category, level|
  ...
end

But I still don't know, how to use it... I'll be glad for every hint!

Thank you so much

Upvotes: 0

Views: 816

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

If you add the optional depth field, you can get the results in this manner:

count = Category.where(depth: 1).count

Upvotes: 0

map7
map7

Reputation: 5126

You could loop through all the categories and count the items on level 1.

With in Rails console try the following:

count = 0
Category.each_with_level(Category.all) do |account, level|
    count += 1 if level == 1
end
puts count

And to print the items you could try this:

Category.each_with_level(Category.all) do |account, level|
    puts "#{level} - #{category.name}"
end

Upvotes: 1

Related Questions