开发者

ruby/rails - creating an inverted tree from active record find

I have been playing around with this and wanted to get a second opinion.

Here is the problem -

I want to order these res开发者_开发知识库ults by who the person reports to (i.e. there boss)

--- 
- !ruby/object:History 
 attributes: 
  id: 1392
  job_title: Global Leader
  reports_to:
  attributes_cache: {}

- !ruby/object:History 
 attributes: 
  id: 1393
  job_title: Programme Organiser
  reports_to: 1392
  attributes_cache: {}

- !ruby/object:History 
 attributes: 
  id: 1394
  job_title: Programme Lead
  reports_to: 1393
  attributes_cache: {}

they will be outputted in json so will look like this

{id: 1394, some_attributes, children: {id: 1393, some_attributes, children: { etc }}

I wrote this function but it started to look really bad

 candidates.each do |candidate, index|
  if !candidate.reports_to.present?
    structure << candidate
    candidates.to_a.delete_if {|candidate_inst| candidate_inst == candidate}
    candidates.each do |child|
      if child.reports_to == candidate.candidate_id
        # add child to children of parent
      end
    end
 end

There must be a cleaner way of doing this ??

Thanks, Alex


maybe you can achieve same goal using Enumerable#group_by, see docs

candidates.group_by(&:reports_to)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜