2

次のようなツリーにすべての作成者を集める必要があります。

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

ありがとう

4

1 に答える 1

1

モデルに単一テーブル継承を使用していると思いPostますが、独自のバージョンをロールしたかどうかはわかりませんでした。祖先の宝石を使用することをお勧めします。次に、次のような簡単なことを行うことができます。

@authors = post.subtree.collect(&:author).uniq
于 2012-10-27T17:42:53.000 に答える