简体   繁体   中英

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)

What is the best approach in Ruby on Rails to collect all authors (post belongs_to author)? 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. I'd recommend to use the ancestry gem . Then you could do something simple like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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