I've two models:
Post
- category_id
Category (ancestry model)
The category tree looks for example like this:
- Root Category
- Sub Category
Now lets say a post gets categorized to Sub Category. I'm in the Root Category and i would like to see all posts which are in Sub Category as well. Is it possible to get these as well with ancestry?
The category tree always has just one nested level so maybe ancestry is anyways too much..
Thanks in advance
Working example for just one nested level
@category = Category.find(params[:id])
category_ids = @category.children.map(&:id) << @category.id
category_ids = category_ids.join(",")
@posts = Post.recent.where("category_id IN (#{category_ids})").page(params[:page])
Something like
You then request the posts, which have their category-id in the list generated by @category.sucategories, from which you select the id and merge them into a string like '1,5,77'.
Something very very bad to do is (just for fun):
Update: Just thought of some other solution:
All postst are retrieved in one query (thanks to includes), then you iterate over the subcategories and posts.
I suggest that the following would do the trick:
And would also probably be the most efficient way without doing something really horrible.