获取 children 的所有 children 等等

Get all children of children and so on

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

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

所以当我查询 children 节点 A 时。我得到所有 children 作为输出,例如 B C D E F G

 C = Customer.find_by(:id => "SOME_ID")
 C.children #list all children upto one level

所以任何人都可以建议我获得递归的方法children。

客户模型

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

谁能帮帮我。或者建议一种方法来完成这个。

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

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