E
E
eldar_web2018-02-25 09:45:03
ruby
eldar_web, 2018-02-25 09:45:03

Recursion in Ruby. How to implement?

Let's say there is a model of departments with a "master - child" relationship:

District
id
id_parent

How can I iterate over all id-shniki starting from the main to the last child?
Do not offer gems!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SilentFl, 2018-02-26
@SilentFl

Monsieur wishes strange))

def walk_tree(root_id)
  root_item = Distinct.find(root_id)
  items = Distinct.where(parent_id: root_item.id)
  items.each { |item| walk_tree(item.id) }
end

If the model is in the database, then there will be a bunch of requests, you can get rid of this by immediately reading all the entries in the hash and searching for it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question