简体   繁体   English

有没有更好的方法来绘制孩子和大孩子的记录?

[英]Is there a better approach to map records of children and grand children?

I need to collect all authors in a tree like: 我需要将所有作者收集在像这样的树中:

parent
|
+- child #1
|
+- child #1
|  |
|  +- grand child #1
|  |
|  +- grand child #2
|
+- child #2
...

(The origin post can have n childs and every child can also have m childs. Maximum depth from origin post is 2: Post - Child - Grandchild) (原始帖子可以有n个孩子,每个孩子也可以有m个孩子。从原始帖子开始的最大深度为2:Post-Child-Grandchild)

What is the best approach in Ruby on Rails to collect all authors (post belongs_to author)? Ruby on Rails中收集所有作者的最佳方法是什么? My current approach is the following, but it seems not really performant: 我当前的方法如下,但似乎并不是很有效:

def all_authors_in(post)
  @authors = Array.new
  @authors << post.author

  post.children.each do |child|
    @authors << child.author
    child.children.each do |grandchild| 
      @authors << grandchild.author
    end
  end

  @authors.map{|u| u.id}.uniq
end

Some code from the model: 该模型的一些代码:

class Post < ActiveRecord::Base
  belongs_to :parent, class_name: 'Post'
  has_many :children, foreign_key: :parent_id, class_name: 'Post', :dependent => :destroy
#...
end

Thanks 谢谢

I assume you are using single table inheritance for your Post model, but you didn't say if you rolled your own version. 我假设您对Post模型使用单表继承,但是您没有说是否滚动了自己的版本。 I'd recommend to use the ancestry gem . 我建议使用祖先宝石 Then you could do something simple like this: 然后,您可以执行以下简单操作:

@authors = post.subtree.collect(&:author).uniq

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

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