很棒的嵌套集 - 如何获得任何子树的语句?

发布于 2024-12-17 11:14:24 字数 303 浏览 2 评论 0原文

我是新手,正在玩这个宝石。我在数据库中有一个树结构。但现在我正在努力寻找一种方法,如何获取例如第一级的项目声明...或第一级或第二级的计数项目...

任何人都可以帮助我解决这个问题吗? 我在 GitHub 上发现了这个循环的项目声明:

Category.each_with_level(Category.root.self_and_descendants) do |category, level|
  ...
end

但我仍然不知道如何使用它......我会很高兴得到每一个提示!

太感谢了

I am a newbie and I am playing with this gem. I have in database a tree structure. But now I am struggling with a way, how to get a statement of items for example on the first level... or the count items on the first or second level...

Could anyone help me please with this problem?
I found at GitHub this loop for a statement of items:

Category.each_with_level(Category.root.self_and_descendants) do |category, level|
  ...
end

But I still don't know, how to use it... I'll be glad for every hint!

Thank you so much

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三生池水覆流年 2024-12-24 11:14:24

您可以循环遍历所有类别并计算第 1 级上的项目。

在 Rails 控制台中尝试以下操作:

count = 0
Category.each_with_level(Category.all) do |account, level|
    count += 1 if level == 1
end
puts count

要打印项目,您可以尝试以下操作:

Category.each_with_level(Category.all) do |account, level|
    puts "#{level} - #{category.name}"
end

You could loop through all the categories and count the items on level 1.

With in Rails console try the following:

count = 0
Category.each_with_level(Category.all) do |account, level|
    count += 1 if level == 1
end
puts count

And to print the items you could try this:

Category.each_with_level(Category.all) do |account, level|
    puts "#{level} - #{category.name}"
end
因为看清所以看轻 2024-12-24 11:14:24

如果添加可选的 深度 字段,则可以通过以下方式获取结果:

count = Category.where(depth: 1).count

If you add the optional depth field, you can get the results in this manner:

count = Category.where(depth: 1).count
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文