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 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
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.
Thank you for the nice test. It was fun to me. :)