I'm having a problem trying to get a recursive method to work in rails/ruby. The purpose is to find all ancestor categories of a given category based on the parent_id. The current method does return the right ancestor categories, but it is nesting the array. I think this is because I'm initializing the category_ancestors array, and then it is getting reinitialized as the method recurses through itself. I'm trying to figure out how to change this so that I get a single level array with the category attributes rather than how it is outputting the data now.
def self.get_ancestors(category)
category_ancestors = [] # <-- this seems to be the problem
category_ancestors << category.attributes
if category.has_parent?
category.get_parent.each do |parent_category|
category_ancestors << get_ancestors(parent_category)
end
end
category_ancestors.reverse
end
This returns something like which is nesting the arrays (but I need them all at the same level):
---
- - - name: Category 1
id: 1
created_at: 2011-09-04 22:56:43.198413 Z
updated_at: 2011-09-07 00:14:09.934813 Z
parent:id
- name: Category 2
id: 2
created_at: 2011-09-04 22:56:43.198413 Z
updated_at: 2011-09-07 00:14:09.934813 Z
parent:id: 1
- name: Category 3
id: 3
created_at: 2011-09-04 22:56:43.198413 Z
updated_at: 2011-09-07 00:14:09.934813 Z
parent:id: 2