次のようなツリーにすべての作成者を集める必要があります。
parent
|
+- child #1
|
+- child #1
| |
| +- grand child #1
| |
| +- grand child #2
|
+- child #2
...
(元のポストにはn人の子を含めることができ、すべての子にm人の子を含めることもできます。元のポストからの最大深度は2です:ポスト-子-孫)
すべての作成者を収集するためのRubyonRailsの最良のアプローチは何ですか(投稿belongs_toauthor)?私の現在のアプローチは次のとおりですが、実際にはパフォーマンスが良くないようです。
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
モデルからのいくつかのコード:
class Post < ActiveRecord::Base
belongs_to :parent, class_name: 'Post'
has_many :children, foreign_key: :parent_id, class_name: 'Post', :dependent => :destroy
#...
end
ありがとう