开发者

rails search a category for sub categories

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 the 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.

//this is what i tried first
@category = Category.find(params[:id])
@child_products = @category.descendants.products

//this actually works but only for one
@child_products = @category.descendants.first.products

because a product belongs_to a Category and a Category has many products. However, the descendants function gives back an array of all the descendants. How do I filter through those and get the combined products?


Move the named scope to your Product model, since that's what you're trying to display.

# product.rb    
named_scope :for_category_ids, lambda {|ids| {:conditions => {:category_id => ids}}}

Then in your controller:

@products = Product.for_category_ids(@category.descendants.map(&:id))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜