本文介绍了Rails的祖先:获取孩子的祖先模型记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

Post
 - category_id

Category (ancestry model)

类别树看起来像这样:

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

预先感谢

仅一个嵌套级别的工作示例

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

这篇关于Rails的祖先:获取孩子的祖先模型记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:36