1
매우 간단한 재귀 메서드를 작성하려고하지만 작동하지 못합니다. 나는 여기에 같은 ID를 가진 간단한 코멘트 계층 구조를 가지고 :모델의 단순 재귀 메서드
이1--
2--
4--
3--
5--
는 이제 배열에 자신의 ID를 저장하려면 (트리 순서) [0]=1, [1]=2, [2]=4, [3]=3, [4]=5
내가
def comment_tree
comment = self.comments.find(1) #it's temporary, just to check if it works
return recur(comment,0)
end
private
def recur(comment,i)
@tree[i]=comment.id #added attr_accessible :@tree
if comment.children.any?
comment.children.each {|c| recur(c,i+1)}
else
return
end
@tree
end
와 엔트리 모델이 배열을 구축 시작
블록이 동일한 카운터 인수 recur(4,2)
및 recur(3,2)
을 두 번 실행하므로이 방법은 작동하지 않습니다. 이 arras 인덱스를 유지하려면 글로벌 $ i와 같은 것이 필요하지만 더 나은 방법이 있어야합니다. @tree도 마찬가지입니다. 재귀 메서드에서 반환 매개 변수로 사용하기 위해 모델에 새 변수를 추가해야합니까? 다른 곳에서는 사용하지 않을 것입니다.
def comment_tree
comment = self.comments.find(1)
tree = []
recur(comment, tree)
tree
end
private
def recur(comment, acc)
acc << comment.id
comment.children.each {|c| recur(c, acc) }
end
화려 :) 감사합니다, 너무 간단합니다 이것에 대해 어떻게 –