Search code examples
mysqlsqlruby-on-railstreeorgchart

Rails: Find all children from the same generation


In my application I have positions. Each position has one parent and many children positions. How can I navigate the tree and find all positions that are in the same generation?

Currently I have this:

def org_chart_level
  ps = self
  level = 10
  while ps do
    break if ps.reports_to == nil
    ps = ps.reports_to
    level += 10
  end
  if self.reports_to
    siblings = self.reports_to.responsible_for
  else
    siblings = [self]
    puts siblings
  end
  "#{level}-#{siblings.index(self) + 1}"
end

This almost works because it can give me the level of a position and it can tell me which sibling it is of the parent, but it cannot tell me which sibling it is in the generation.

Expected level for each position.

1.1
  -2.1
     -3.1
  -2.2
     -3.2

Actual level:

1.1
  -2.1
     -3.1
  -2.2
     -3.1

Solution

  • I ended up storing the positions generation in the database before it is saved.

    before_save :find_generation

    def find_generation
      ps = self
      i = 0
      while ps do
        break if ps.reports_to == nil
        ps = ps.reports_to
        i += 1
      end
      self.generation = i
    end
    

    And then when I need to generate the org chart level:

    def org_chart_level
      ps = self
      level = 10
      while ps do
        break if ps.reports_to == nil
        ps = ps.reports_to
        level += 10
      end
      generation = organization.positions.where(generation: self.generation) #position belongs to organization.
      "#{level}-#{generation.index(self) + 1}"
    end