首页 > 解决方案 > 获取孩子的所有孩子等等

问题描述

我正在使用 MongoDb 作为数据库。

我想要所有的孩子的孩子等等。让我们假设

因此,当我查询子节点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

谁能帮帮我。或者建议一种方法来实现这一点。

标签: ruby-on-railsrubymongodbruby-on-rails-3mongoid

解决方案


您可以添加自定义方法来收集客户的所有孩子,以及孩子的孩子,等等。

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

推荐阅读