Is there a better approach to map records of children and grand children?
-
14-07-2021 - |
Question
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
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow