Recursvie Search Refactoring

Hi, All

I was wondering if somebody could suggest a better way to do it. I got it working but it's a bit dirty and returns too much extra fluff.

I'm trying to do a recursive search on an a collection of Objects.

A better way to illustrate it is an Org Chart.

Lets say I have Employee and ManagedByEmployee Objects

Employee hold user id , name, address, etc.... also: has_many :managed_by_employees, :dependent => :destroy

ManagedByEmpoyee holds 3 attributes: id, employee_id and managed_by_employee_id also: belongs_to :employee belongs_to :managed_by_employee, :class_name => "Employee", :foreign_key => "managed_by_employee_id"

This allows me to do any searches 1 level deep. I can find who this particular employee manages and who he is managed by. That trivial.

What I want to do is a drill down search.

Let's say I do:    @emps = find_all_by_managed_by_employee_id(3) This would return me all of the empployees that are managed by employee #3, lets say I want to go through that list and check all of the employees and see who they manage, and so on and so forth - until I reach the bottom, where I find employee that don't manage anyone.

Then I want a similar function that goes in the other direction.

I wrote a model methods that handle that = but there are 2 problems with them: 1) They return too many duplicate records - and I have to clean them up at the end. 2) I return all of the employees that employee # 3 manages but, I can't tell how they relate to employee 3 (well I can go through the chain again and figure it out) But there's got to be a btter way to do it then running more sql statement.

Below are my model functions

def self.find_employees_that_i_manage(employee, employees_array)   arr = employees_array   arr += @managed_employees = find_all_by_managed_by_employee_id(employee)     unless @managed_employees.empty?       @managed_employees.each do |s|         arr += find_employees_that_i_manage(s.employee_id, arr)       end     end   arr |= arr end

def self.find_employees_that_manage_me(employee, employees_array)   arr = employees_array   arr += @managed_by_employees = find_all_by_employee_id(employee)     unless @managed_by_employees.empty?        @managed_by_employees.each do |s|           arr += find_employees_that_manage_me(s.managed_by_employee_id, arr)        end     end   arr |= arr end

Here is how I call them from controller:   @manages_employees =      managedByemployee.find_employees_that_i_manage(params[:id], p=)   @managed_by_employees =      managedByemployee.find_employees_that_manage_me(params[:id], p=)

Anyone has any suggestions?