获取所有孩子的孩子,依此类推

时间:2018-07-16 20:35:56

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

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

我要所有孩子的孩子等等。 假设

  • A有B&C子女
  • B有D&E孩子
  • D有F&G子女

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

 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

有人可以帮助我吗?或提出一种实现此目的的方法。

1 个答案:

答案 0 :(得分:4)

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

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
相关问题