Rails ancestry: Get children records of ancestry m

2019-08-31 06:29发布

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

2条回答
干净又极端
2楼-- · 2019-08-31 06:40

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.

查看更多
别忘想泡老子
3楼-- · 2019-08-31 06:42

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.

查看更多
登录 后发表回答