【发布时间】:2012-10-27 17:17:17
【问题描述】:
我需要在树中收集所有作者,例如:
parent
|
+- child #1
|
+- child #1
| |
| +- grand child #1
| |
| +- grand child #2
|
+- child #2
...
(原始帖子可以有n个孩子,每个孩子也可以有m个孩子。原始帖子的最大深度为2:帖子-孩子-孙子)
在 Ruby on Rails 中收集所有作者(post belongs_to author)的最佳方法是什么?我目前的方法如下,但它似乎不是很有效:
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
谢谢
【问题讨论】:
标签: ruby-on-rails arrays map collect