E
E
eldar_web2018-02-03 21:28:21
ruby
eldar_web, 2018-02-03 21:28:21

How to recurse?

Let's say there are categories and nested subcategories.
Here is my recursion code (Ruby):

def recurs(category_id)
    @list << category_id
    Category.where(parent_id: category_id).each do |category|
      recurs(category.id)
    end
  end

And this is how I call it:
@list = []
recurs(7)

As a result, @list is what I need.
But the call doesn't look normal.
How to carry out a recursion, so that at least it would be possible to sort through the id-shniks like this: ???
@list = recurs(7)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
YetiGooBye, 2018-02-27
@eldar_web

Late but...

def recurs(category_id, list=[])
  list << category_id
  Category.where(parent_id: category_id).each do |category|
    recurs(category.id, list)
  end
  list
end
recurs 7

V
Vasily Shakhunov, 2018-02-06
@inf

More humane like this

def recurs(category_id)
    list << category_id
    Category.where(parent_id: category_id).each do |category|
      recurs(category.id)
    end
    list
  end

@list = recurs(7)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question