开发者

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

开发者 https://www.devze.com 2023-03-09 15:48 出处:网络
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)

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

精彩评论

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

关注公众号