1
Nov

Acts_as_tree_on_steroids plugin

posted by gchatz 79 comments rails

We’ve been using a home-made extension of acts_as_tree on our production site for quite some time. We finally found some time to release it as a plugin You can find it on github. It’s not anything special, but it may give you some ideas for doing similar things.

In a nutshell

Extend classic acts_as_tree, acts_as_nested_set to support:

  • Fetching descendants with one sinqle query
  • Fetching anscestors with one single query
  • Fetching the root node of a node with one query
  • Store the level of each node
  • Store the children count of each node
  • Configure a “family” based on the level (depth) that can be different from the root node

Why?

The problem with classic acts_as_tree is that you need a large number of queries to retrieve the ascendants or descendants of a node. If you want the path of a node with a level of N , you need N – 1 queries. If you want all the children and grandchildren and so forth , you need to recurse at least N times. This can become a pain if your tree is more than 3 or 4 levels.
Acts as nested set offers functionality to retrieve all descendants of a node with a single query, but you can’t do the same for ancestors which is very usefull for a number of things (i.e breadcrumbs)

If your application offers a hierarchical based browsing, you’ll probably need to query the tree all the time to create breadcrumbs or lists with subcategories. Classic examples are ecommerce applications, price comparison sites etc.

Families:

In ecommerce applications it’s very common to have families of products or categories. For example:

Electronics
| -> Computers & Peripherals
| --> Storage
| ----> Hard Disks
| --------> SSD
 

The root node of SSD is Electronics but that’s not the actually family of products because it covers a really big range. The actual family (depending on the application logic) can be Computers & Peripherals or Storage. If family_level is set to 1 for example, the family will be Computers & Peripherals.

Installing

As a plugin:

script/plugin install http://github.com/bandito/acts_as_tree_on_steroids.git

Usage

Your model must have the following database tables:

  • parent_id (lnteger)
  • id_path (string)
  • children_count (integer)
  • level (integer)

Optionally you can enable family support by adding the following column.

  • family_id (integer)

You should add indexes for id_path, parent_id and family_id (level and children_count will probably have a low cardinality , but you can index them anyway)

Then include the helper in your model.

class Category
	acts_as_tree_on_steroids :family_level => 1
end

How does it work

When a node is created or changes parent the id_path reflects the node path from the root to the node as a comma seperated value of ids.
For example a really small tree would look like this

1
1,2
1,2,3
1,2,4
1,5
1,6
1,6,11
1,6,11,17
20
20,21
20,21,22
20,21,23
20,21,23,25

If we want to get the descendants of node with id_path 1,6 then we would query for “id_path like ‘1,6,%’” which would match 1,6,11 and 1,6,11,17.
The database will use the index on id_path since it’s not starting with a wildcard.

Likewise, if we wanted the ancestors of the node with id_path 1,6,11,17 we would just query for “id in (1,6,11,17)” to get them with a single query.

When to use it

  • You have a category tree that rarely changes but you are doing breadcrumbs and tree representations all the time.
  • You have the need to query for i.e products that belong to the current node and the descendant nodes

When not to use it

  • If your tree changes frequently then the overhead of the tree traverse can be a pain.
  • You don’t need to know the hierarchy of the node.
Comments (79)

Pin Peter said on Nov 23, 03:52 PM:

Can a nested resource be from other Models? For example, make belongs_to :manufacture and make has_many :series through => product.

When creating a new make I can create an association to a manufacture or when creating a new product I can create an association to manufacture, model and series?

Pin العاب said on Jan 27, 04:23 PM:

Thank you for your topic
The subject of bitter, sweet, beautiful, moon
Accept traffic
Gisele thanks from me to you
Mra thanks
To the meeting ..

Pin dantelsandigi said on Feb 03, 09:32 PM:

When not to use it

* If your tree changes frequently then the overhead of the tree traverse can be a pain.
* You don’t need to know the hierarchy of the node.

Pin videoizle said on Feb 03, 09:38 PM:

SSD kök düğümü Elektronik ancak çünkü gerçekten büyük bir aralığı kapsar ürünlerin aslında aile değil. Uygulama mantığını bağlı olarak gerçek ailesi () Bilgisayar ve Çevre Birimleri veya Depolama olabilir.

Pin videoizle said on Feb 03, 09:40 PM:

When to use it

* You have a category tree that rarely changes but you are doing breadcrumbs and tree representations all the time.
* You have the need to query for i.e products that belong to the current node and the descendant nodes

Pin دردشة said on Feb 10, 07:27 PM:

If your tree changes frequently then the overhead of the tree traverse can be a pain.

Pin العاب طبخ said on Mar 07, 04:05 PM:

We didn't make it , but we are close:

* Your comment must be at least 10 characters

Pin العاب بنات said on Mar 07, 04:06 PM:

fffdfdffggfdfgfgdfggfgfd

Pin العاب سيارات said on Mar 07, 04:06 PM:

fdgfgdffggfdffgd

Pin mania virtual said on Mar 09, 08:43 PM:

your text is good

Pin Christian Louboutin said on Mar 29, 01:02 PM:

The first thing is to make it clear what the style of your dress is and what you are going to outline which part of your body. For instance, are you intending to show your long legs or sexy foot fingers? After that, your task is to find the shoes for you.

Pin Justin Tv said on Apr 10, 02:58 PM:

Thank you very much this information.

Pin seni seviyorum said on Apr 10, 03:23 PM:

Thanks admin very nice post

Pin mp3 dinle said on Apr 10, 04:22 PM:

nice post.

thanks for useful info...

Pin oyun indir said on Apr 10, 05:47 PM:

thats good very good.

Pin Dental jobs said on Apr 12, 11:19 AM:

# You have a category tree that rarely changes but you are doing breadcrumbs and tree representations all the time.

Pin Professionelles Fotoshooting said on Apr 16, 11:27 PM:

Really cool post - thank you very much - the post help me :-)

Pin Rubecca Jakes said on Apr 21, 09:54 AM:

This new version is very useful especially to know the hierarchy of nodes which is very crucial for me at least.

Pin Zreviews said on Apr 26, 02:48 AM:

It 's really hard for me. May be, I have to learn a lot of things.

Pin Huntsman said on Apr 26, 02:55 AM:

Thanks. It 's a nice plugin.

Pin 000 200 said on May 12, 07:28 AM:

It 's a nice plugin.

Pin Metin Kılıç said on May 13, 05:33 AM:

Thanks your text is good

Pin internet marketing said on May 13, 11:19 AM:

Great plug in I'll make use of this.

Pin groom speech said on May 13, 11:21 AM:

Got it downloaded and installed with no problems thanks guys.

Pin star ebooks said on May 14, 07:05 AM:

Seems to be an application that helps you to make your job simpler! It is a welcome change when we get suggestions like this which will help us save time but at the same time, not lose the quality of our work. With all the details given, it won't be difficult for anyone to try it! They have also tipped us with when and when not to use it and the reasons for doing so!! So this home-made extension plug will definitely make your work easier especially in the fields of ecommerce applications, price comparison sites, etc. Good work and keep going!!

Pin refurbished cubicles said on May 18, 04:28 PM:

Got it downloaded and installed with no problems thanks guys.

Pin write essay said on May 19, 08:40 PM:

good post. I like this post

Pin Dental Jobs said on May 20, 11:18 AM:

Interested post, like the name inparticular. Good article, found useful. cheers

Pin Clara said on May 20, 10:57 PM:

Like this, its interesting. Now I go to install the plugin :-)

Pin atics said on May 31, 07:40 AM:

using tree for programming method is very useful, specially for large number queries..

Pin bilgi said on Jun 05, 10:30 PM:

Your site is very nice touches on a beautiful subject

Pin TV said on Jun 09, 11:33 PM:

Thanks werry good!

Pin spain villas said on Jun 17, 12:15 PM:

Thank you for this blog post. The commenter, then, becomes the critic who shapes the writer's next content. So I want to encourage you to keep on blogging in the same style as you writing style is really perfect.

Pin smuckers natural peanut butter said on Jun 18, 01:05 PM:

That is rather particular and rather great to acknowledge that we have such an opportunity to overcome all the obstacles and enjoy reading one’s thoughts and ideas which could be of great help and value in our everyday life.

Pin توبيكات said on Jun 18, 03:56 PM:

thanx for all :)

Pin توبيكات جديده said on Jun 18, 03:58 PM:

your text is good

Pin TuaTua said on Jun 19, 05:42 PM:

Thanks for this blog post. The commentator, then the critic, the content forms the next writer. Therefore, I encourage you to continue blogging in the same way that the writing style is perfect.

Pin Tua said on Jun 21, 08:35 AM:

This new version is very useful to know the particular hierarchy of nodes, which is very important to me at least. Really cool post - thank you very much

Pin pariuri sportive online said on Jun 21, 09:30 PM:

well worth the read.I found it very informative as I have been researching a lot lately on practical matters such as you talk about...

Pin بنات said on Jun 22, 01:39 PM:

thank u my dae

Pin العاب said on Jun 22, 01:40 PM:

thank u my dae

Pin منتديات said on Jun 24, 11:29 PM:

This new version is very useful to know the particular hierarchy of nodes, which is very important to me at least. Really cool post - thank you very much

Pin منتديات said on Jul 03, 01:22 AM:

Found it a great launch
I thank you very much
Appreciation and respect
I liked your topic
I wish you success

Pin bijuterii said on Jul 03, 04:19 PM:

Thanks a lot bijuterii.

Pin اعلانات مبوبه said on Jul 05, 06:03 PM:

thank u my dae

Pin pokerplus said on Jul 05, 06:18 PM:

Great idea. Faster is definitely better.

Pin العاب بنات said on Jul 09, 04:18 AM:

العاب بنات

Pin vehicle transport said on Jul 10, 05:32 AM:

The problem with classic acts_as_tree is that you need a large number of queries to retrieve the ascendants or descendants of a node. If you want the path of a node with a level of N

Pin v-pills said on Jul 10, 09:02 PM:

vpills marketim...

Pin v-pills said on Jul 10, 09:03 PM:

vpillssss.....

Pin çiçek sepeti said on Jul 12, 05:38 AM:

Devlet Bakanı ve Başbakan Yardımcısı Cemil Çiçek, Meslek Yüksek Okulları temel atma törenlerine katılmak için geldiği Yozgat’ta devlet olarak eğitime yeteri kadar önem verilmediğini ilginç bir örnekle anlattı. Cumhurbaşkanı Abdullah Gül’ün Nijerya ziyaretine katıldığını aktaran Cemil Çiçek, orada Türk okulları olduğunu, Nijeryalıların Türkçeyi öğrendiklerini fakat, Hakkari’dekine, Diyarbakır’dakine halen Türkçe’yi öğretemediklerini söyledi. Çiçek, bu durumun devletin eğitime yeteri kadar önem vermemesinden kaynaklandığını ve bedelini de ağır ödediğini söyledi.

Pin çiçek said on Jul 14, 08:16 AM:

Devlet Bakanı ve Başbakan Yardımcısı Cemil Çiçek, Meslek Yüksek Okulları temel atma törenlerine katılmak için geldiği Yozgat’ta devlet olarak eğitime yeteri kadar önem verilmediğini ilginç bir örnekle anlattı. Cumhurbaşkanı Abdullah Gül’ün Nijerya ziyaretine katıldığını aktaran Cemil Çiçek, orada Türk okulları olduğunu, Nijeryalıların Türkçeyi öğrendiklerini fakat, Hakkari’dekine, Diyarbakır’dakine halen Türkçe’yi öğretemediklerini söyledi. Çiçek, bu durumun devletin eğitime yeteri kadar önem vermemesinden kaynaklandığını ve bedelini de ağır ödediğini söyledi.

Pin منتديات said on Jul 14, 08:27 AM:

thanks a lot's

Pin مركز تحميل said on Jul 15, 01:54 AM:

sdfsad ds fsd f sdf sd fsd f sd fsd f sd fsd sdf sd f df asf sd sd f sdf ds fr ds sd g g f g fgds

Pin economic crisis said on Jul 17, 03:09 AM:

you have the need to query for i.e products that belong to the current node and the descendant nodes

Pin Email Marketing said on Jul 17, 09:04 PM:

I think you'll receive pretty interesting responses, this article will be very beneficial to many people in more than one ways. Thanks for posting!

Pin Hermes birkin said on Jul 19, 10:34 AM:

Hermes birkin

Pin Inchirieri masini said on Jul 21, 04:13 PM:

I would not recommend it at all. If you like simple things, than just keep it simple. Complicated things are complicating your life.

Pin LG HDTV said on Jul 22, 06:30 PM:

Can you further explain this: You should add indexes for id_path, parent_id and family_id (level and children_count will probably have a low cardinality , but you can index them anyway)

Thanks!

Pin Hostess said on Jul 25, 09:45 AM:

Why? Come on. I had tried 4 or 5 times with no luck. Maybe I have the brain of an monkey or maybe it's just not as nicely laid out.

Pin wedding website said on Jul 26, 07:27 PM:

cool, thanks

Pin Nude TV said on Jul 26, 08:33 PM:

When a node is created or changes parent the id_path reflects the node path from the root to the node as a comma seperated value of ids.

Pin produtos da china said on Jul 26, 10:12 PM:

Excellent article, awesome content found here.

Pin bijuterii argint said on Jul 27, 04:44 PM:

nice blog I love it!!

Pin Flyer Design said on Jul 30, 07:52 PM:

I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true.

Pin صدفة said on Aug 05, 10:13 AM:

Pin carpet cleaner Monterey said on Aug 07, 08:54 AM:

It was the best medicine for my life. Why? I just trying to do this with slight mistake about two hours but now i get it alright. Thank you very much.

Pin سعودي said on Aug 07, 12:23 PM:

Thank you for the wonderful explanation of the topic was the application of an integrated explanation at the following locations
http://www.saudicol.com/
http://www.7lahm.com/
http://www.iraqcol.com/
http://www.lightce.com/

Pin carpet cleaner monterey said on Aug 07, 01:53 PM:

Nice tool to have in the webmaster's pocket. Love to see such kind of nice tool introducing posts. Making a bookmark of it. Will catch you every time you give something new.

Pin plastic garden chairs said on Aug 09, 03:05 AM:

I never tried steroids, but this plugin is interesting.

Pin hand sanitizer said on Aug 17, 02:26 AM:

Intresting pluggin whats the plugin in for?

Pin camel cig said on Aug 18, 12:10 PM:

Acts_as_tree_on_steroids plugin is usedfull,It causes inquiry more convenient .

Pin UGG Classic Cardy Boots said on Aug 20, 09:48 AM:

adherheahrh

Pin natural tinnitus cures said on Aug 24, 03:11 PM:

It all helped me a lot. I saved time and I less stressed right now after reading it and doing it. Thank you for your input.

Pin men's down jackets said on Aug 29, 04:11 PM:

Ounce for ounce there is nothing that insulates against the cold quite like goose down. Men's Canada goose expedition parka understands this and has created a line of men's down jackets that help keep the cold of outdoor winter activities at bay. And with 40 years of outdoor gear design and testing experience you know you are getting a goose jackets that is durable and will stand up to whatever you throw at it.

Pin exchange rate said on Aug 31, 04:14 AM:

This is great and very helpful.thanks

Pin saltna said on Aug 31, 05:12 AM:

Excellent article, awesome content found here.

Pin dhf said on Sep 03, 12:26 AM:

شات -
دردشه - دردشة -
شات كتابي -
دردشه كتابيه -
العاب فلاش

Pin دردشه كتابيه said on Sep 03, 12:41 AM:

شات -
دردشه - دردشة -
شات كتابي -
دردشه كتابيه -
العاب فلاش

Drop a comment: