简体   繁体   English

Rails的祖先:获取孩子的祖先模型记录

[英]Rails ancestry: Get children records of ancestry model

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

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. 如果没有做真正可怕的事情,那可能也是最有效的方法。

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'. 然后,您请求这些帖子,这些帖子的类别ID在@ category.sucategories生成的列表中,您可以从中选择ID,然后将其合并为类似“ 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. 所有postst都会在一个查询中检索到(感谢include),然后您遍历子类别和发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM