示例代码的参数名、使用等有些不规范,希望能暂时忽略一下。。。
employee 的上下级关系大概是个树结构,但是经过一段使用后有部分比较混乱,旧的递归方法变成死循环了
暂时改用了暴力获取的方法获取全部下属
需要改造的方法是 def get_all_subs,目前有试过其实数据最多到第四层 sub_ids_4 就结束了
自己有思考过改造成递归,大概是把每次算完的结果都当参数传递到下一个递归中,但是就是实现不出来,所以想请教一下。。。
贴上代码
# 这个是在整数类型中自己加的方法,结果是用整数获取Employee对象,如 Employee.find(1) == 1.to_employee
def to_employee
Employee.find(xx)
end
class Employee
# 属性 id , max_level
attr_accessor :id, :max_level
# 获取的直属下级的员工,返回结果是一个一维数组
def all_sub_ids
[1,2,3,4,5,6.....]
end
# 获取所有下属的员工id现在如下
# max_level > 1的才会需要找all_sub_ids
def get_all_subs
result = []
sub_ids_1 = [id].map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_1.blank?
result += sub_ids_1
sub_ids_2 = sub_ids_1.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_2.blank?
result += sub_ids_2
sub_ids_3 = sub_ids_2.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_3.blank?
result += sub_ids_3
sub_ids_4 = sub_ids_3.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_4.blank?
result += sub_ids_4
sub_ids_5 = sub_ids_4.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_5.blank?
result += sub_ids_5
sub_ids_6 = sub_ids_5.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_6.blank?
result += sub_ids_6
sub_ids_7 = sub_ids_6.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_7.blank?
result += sub_ids_7
sub_ids_8 = sub_ids_7.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_8.blank?
result += sub_ids_8
sub_ids_9 = sub_ids_8.map{|n| n.to_employee.all_sub_ids}.flatten.compact - result
return result if sub_ids_9.blank?
result += sub_ids_9
result.uniq.compact
end
end