ruby /导轨 : determine how deeply nested an object is

标签 ruby activerecord model nested depth

我认为这是一个一般的 ruby​​ 问题,尽管在我的例子中涉及的对象是 ActiveRecord 模型。

如果我有一个模型可以嵌套在另一个模型中,我如何确定模型的嵌套深度?

即:

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 和它的根之间有多少层?

谢谢!

最佳答案

像这样的东西应该可以解决问题:

def depth
  parent.nil? ? 0 : 1+parent.depth
end

关于 ruby /导轨 : determine how deeply nested an object is,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5196256/

相关文章:

python-3.x - 加载相同保存的模型后,Keras 模型精度不同

Ruby 电子邮件检查 (RFC 2822)

ruby - 将 ruby​​ 日期显示为 RFC 3339 时间戳

mysql - Google App Maker - 引用外部 MySql 数据库中的多个表

ruby-on-rails - Rails/Postgres 查询 Hstore 是否存在

database - 在数据库中存储耗时的最佳方法是什么

python - python sklearn中的拟合方法

ruby - 如何为命名空间类定义 Fabricator

ruby-on-rails - Rails 的动态菜单(在一个 View 中引用两个 Controller 的输出)

ruby-on-rails - 友情模型,如何判断2个用户之间是否已经存在友情模型