Items
are organized in folder/tree-like structure via parent_id
attribute. So it is possible to create the following hierarchies:
The problem is - I can not think of an elegant way to retrieve all subitems tree for an Item
. One solution is to use recursion.
My recursive solution (recursive_subitems
method) does not work currently. But even if it will work - I am interested if there are any other alternatives to recursion? Maybe some tricky SQL query?
# == Schema Information
#
# Table name: items
#
# id :integer not null, primary key
# name :string
# parent_id :integer
class Item < ActiveRecord::Base
# for item with ID 1 must return items with IDs [2, 3]
def immediate_subitems
Item.where(parent_id: self.id)
end
# My failing attempt to create a recursive function...
def recursive_subitems(parent_id)
items_ids = Item.where(parent_id: parent_id).map(&:id)
items_ids.each do |item_id|
recursive_subitems(item_id)
end
items_ids
end
# for item with ID 1 must return items
# with IDs [2,3,4,5,6,7,8,9,10,11]
def all_subitems_tree
recursive_subitems(self.id)
end
end