I am using MongoDb as database.
I want all the children of children and so on. Lets Suppose
So when I query for children node A. I get all the children as output such as B C D E F G
C = Customer.find_by(:id => "SOME_ID")
C.children #list all children upto one level
So can anyone suggest me the way, to get recursive children.
Customer model
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
Can anybody please help me out. Or suggest a way to accomplish this.
You can add a custom method to gather all the children of a customer, and children of children, and so on.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With