user984621 user984621 - 1 year ago 74
MySQL Question

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|

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

Thank you so much

Answer Source

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
puts count

And to print the items you could try this:

Category.each_with_level(Category.all) do |account, level|
    puts "#{level} - #{}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download