rails search nested set (categories and sub categories)

Posted by bob on Stack Overflow See other posts from Stack Overflow or by bob
Published on 2010-04-18T01:24:57Z Indexed on 2010/04/18 1:33 UTC
Read the original article Hit count: 456

Hello, I am using the http://github.com/collectiveidea/awesome_nested_set awesome nested set plugin and currently, if I choose a sub category as my category_id for an item, I can not search by its parent.

Category.parent
     Category.Child

I choose Category.child as the category that my item is in. So now my item has category_id of 4 stored in it.

If I go to a page in my rails application, lets say teh Category page and I am on the Category.parent's page, I want to show products that have category_id's of all the descendants as well.

So ideally i want to have a find method that can take into account the descendants. You can get the descendants of a root by calling root.descendants (a built in plugin method).

How would I go about making it so I can query a find that gets the descendants of a root instead of what its doing now which is binging up nothing unless the product had a specific category_id of the Category.parent.

I hope I am being clear here. I either need to figure out a way to create a find method or named_scope that can query and return an array of objects that have id's corresponding tot he descendants of a root OR if I have any other options, what are they?

I thought about creating a field in my products table like parent_id which can keep track of the parent so i can then create two named scopes one finding the parent stuff and one finding the child stuff and chaining them.

I know I can create a named scope for each child and chain them together for multiple children but this seems a very tedious process and also, if you add more children, you would need to specify more named scopes.

© Stack Overflow or respective owner

Related posts about nested-sets

Related posts about nested