Question

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])
Était-ce utile?

La solution

I suggest that the following would do the trick:

Post.where(category_id: @category.subtree_ids)

And would also probably be the most efficient way without doing something really horrible.

Autres conseils

Something like

Post.where('subcategory_id in ('+@category.subcategories.select(&:id).join(',')+')')

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):

@mylist = Array.new
Post.all.each do |item|
  @mylist << item if item.subcategory.category = @selectedrootcategory

Update: Just thought of some other solution:

@allposts = Array.new
@selectedrootcategory.includes(:subcategory => :posts).subcategories.each do |subcat|
  @allposts << subcat.posts

All postst are retrieved in one query (thanks to includes), then you iterate over the subcategories and posts.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top