ruby-on-rails - 获取孩子的所有孩子等等
问题描述
我正在使用 MongoDb 作为数据库。
我想要所有的孩子的孩子等等。让我们假设
- A 有 B & C 孩子
- B 有 D & E 孩子
- D有F&G的孩子
因此,当我查询子节点A时。我把所有的孩子都作为输出,比如 BCDEFG
C = Customer.find_by(:id => "SOME_ID")
C.children #list all children upto one level
所以任何人都可以建议我获得递归孩子的方法。
客户模型
class Customer
include Mongoid::Document
field :email, type: String
field :referral_id, type: String
belongs_to :parent, class_name: 'Customer',foreign_key: "referral_id", optional: true
has_many :children, :class_name => 'Customer', :foreign_key => "referral_id"
end
谁能帮帮我。或者建议一种方法来实现这一点。
解决方案
您可以添加自定义方法来收集客户的所有孩子,以及孩子的孩子,等等。
class Customer
def descendants
self.children | self.children.map(&:descendants).flatten
end
end
cust = Customer.find(<id>)
cust.descendants
=> # Array of all the descendants of customer
推荐阅读
- c# - 如何防止HttpClient在发送请求时产生新行?
- swift - 如何在不使用 seague 和 storyboard 的情况下将数据从一个视图控制器传递到另一个视图控制器
- api - API 需要验证码是设计缺陷吗?
- javafx - 从新添加的窗格中分配控制器中的 FXML 元素 - JavaFX
- php - tesseract-php 包装器在本地主机上运行时出现路径错误
- javascript - 防止在页面刷新时重置倒数计时器 - Django & JS
- reactjs - 如何在反应中的 this.state.forEach 语句中抛出错误
- excel - 在 msgbox 提示中使用 inputbox 的输入
- java - 如何从 .csv 文件中拆分数据集以在 java 中进行训练和测试?
- oracle - 如何在客户端机器上部署 oracle apex 应用程序