Topic: Finding all children beneath a certain node in a acts_as_tree model

Dear Railsforum members,

my first application is - not least through your help - making good progress. Today I'm a little stuck with my Organization model:

Company, countries and areas are organized in the model "Organization" with an acts_as_tree association

The users belong_to :areas in the Organization model. Every area has_many :users

+Company
++country_1
+++area_1
----user_1
----user_2
+++area_2
----user_3
----user_4
++country_2
+++area_3
----user_5
+++area_4
----user_6

I looking for a way, to find all users underneath a certain node, lets say, a Find_user method:

Find_users(area_1) -> user_1, user_2

makes no problem, but I don't get it to do

Find_users(country_1) -> user_1, user_2, user_3, user_4

or

Find_users(Company) -> user_1, user_2, user_3, user_4, user_5, user_6

Will I have to step trough the different nodes and collect the users or is there an other, elegant more "Rails-like" method?

Any advice is appreciated

Thanks in advance

Thomas

Re: Finding all children beneath a certain node in a acts_as_tree model

DocTom wrote:

Will I have to step trough the different nodes and collect the users or is there an other, elegant more "Rails-like" method?

Using acts_as_tree? Yes, I'm afraid you will have to step through each node. This is more of a limitation of SQL instead of Rails.

If you want to do this all in one query you an look into acts_as_nested_set. This is similar to acts_as_tree but stores the relationship differently to make it easier to query all children/grandchildren of a node.

However, I've heard acts_as_nested_set is buggy. They might have fixed it though - or you may be able to find a plugin which does something similar and is less buggy.

Railscasts - Free Ruby on Rails Screencasts

Re: Finding all children beneath a certain node in a acts_as_tree model

Hello Ryan,

thanks a lot. acts_as_nested_set looks a little wacky to me...

But a search for "acts_as_nested_set" lead me to the following thread in this forum.

Your "self_and_all_children" method from post #13 works for me.

Regards

Thomas

Last edited by DocTom (2007-02-01 14:46:26)

Re: Finding all children beneath a certain node in a acts_as_tree model

Cool, glad you found that useful. This is still stepping through each node and doing a database query for each step, but if the performance is good enough it is definitely the easiest solution.

You're right, acts_as_nested_set is pretty wacky. See this article on more (non-rails) information on trees in databases.

Railscasts - Free Ruby on Rails Screencasts