ruby on rails 4 - How to retrieve all item's childs? Recursion? Tricky SQL query? -


items organized in folder/tree-like structure via parent_id attribute. possible create following hierarchies: folder structure of items

the problem - can not think of elegant way retrieve subitems tree item. 1 solution use recursion. recursive solution (recursive_subitems method) not work currently. if work - interested if there other alternatives recursion? maybe tricky sql query?

# == schema information # # table name: items # #  id               :integer          not null, primary key #  name             :string #  parent_id        :integer  class item < activerecord::base    # item id 1 must return items ids [2, 3]   def immediate_subitems      item.where(parent_id: self.id)   end    # failing attempt create recursive function...   def recursive_subitems(parent_id)             items_ids = item.where(parent_id: parent_id).map(&:id)     items_ids.each |item_id|         recursive_subitems(item_id)     end     items_ids   end    # item id 1 must return items    # ids [2,3,4,5,6,7,8,9,10,11]   def all_subitems_tree     recursive_subitems(self.id)   end end 

here's working recursive method:

def recursive_subitems(parent_id)     # byebug     result = []     items_ids = item.where(parent_id: parent_id).map(&:id)     return [parent_id] if items_ids.empty?      items_ids.each |item_id|         result << recursive_subitems(item_id)     end     result << parent_id end  def all_subitems_tree     puts "subitems tree #{self.id}"     ids = recursive_subitems(self.id).flatten     ids.pop     item.find(ids) end 

Comments