Skip to content

trinibago/nested_set

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nested set example

It’s a quick implementation of a nested set for categories. A nested set speeds up the search for elements in a hierarchical tree stored in relational database. SELECTs are quicker and map the flexibility as needed. Updates become slower through the nested set (the rate depends on the position where a new category will be added).

Products can be counted using the nested set (look at Product#count_nested).nd try it in your Rails console). The expected parameters can be either an array of Strings or an argument list of Strings. Adding a new category to the nested set is also implemented (look at the callback Category#update_nested_set). The elements of the tree according to the example are also added (look at db/seeds.rb).

The SQL statement for counting elements in a nested set

The SQL statement for a count itself would look like: SELECT COUNT(“products”.id) FROM “products” INNER JOIN categories c, categories p ON c.id = products.category_id WHERE (p.name IN (‘CONSUMABLES’,‘SOFTDRINKS’, ‘DRINKS’) AND c.left BETWEEN p.left AND p.right) GROUP BY products.id

Note

Please note that the SQL statement, generated by Rails looks slightly different. This is due to the odd behaviour of ActiveRecord::QueryMethods#group in combination with ActiveRecord::QueryMethods#count. It would return a Hash of counted items. That’s why I call length on the result, which returns the amount of found products.

Thanks

Thank you for the nice test. It was fun to me. :)

About

Product categories in a nested set structure

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published