我認爲這是一個普通的ruby問題,但在我的案例中涉及的對象是ActiveRecord模型。Ruby/Rails:確定對象的嵌套深度
如果我有一個模型可以嵌套在另一個模型中,我該如何確定模型嵌套的深度?
IE:
Model Root (Level 0)
- Model Level 1
- - Model Level 2
- - Model Level 2
- - Model Level 2
- - - Model Level 3
- - - Model Level 3
- Model Level 1
- Model Level 1
在假設foo
是嵌套三個層次深的模型(如上所示)。如果我打電話foo.parent.parent.parent
,我會得到根模型。
我該如何定義一個方法,如:foo.depth
,它會返回foo和它的根之間有多少級別?
謝謝!
哇!簡單,優雅,非常紅寶石。這工作完美,謝謝! – Andrew 2011-03-04 16:19:30