I’m building an employee directory application and am using self joins so all employee relationships are in one table.
I have subordinates (direct_reports) displaying and I can show an individual’s manager.
Here is my model:
has_many :direct_reports, :class_name => "Person", :foreign_key => "manager_id"
belongs_to :manager, :class_name => "Person"
Here is my view:
<tr><td>Manager:</td><td><strong><%= link_to "Manager", @person.manager %></strong></td></tr>
<tr><td>Direct Reports:</td><td><strong><% @person.direct_reports.each do |person| %>
<%= link_to person.lname + ", " + person.fname, person %><br>
<% end %></strong></td></tr>
However, I haven’t found any way to show the complete reporting hierarchy of the people above in the organization. Yes, I’m showing the manager, but I need to show their manager and their manager, etc. all the way up to the CEO.
I’m assuming that everyone only has one manager (on up the chain).
Any assistance is greatly appreciated.
There isn’t any easy way to do this using a single SQL query (as noted in comments Postgres has support for this), unless you can limit it to a predetermined number of levels. Otherwise, you can simply make a loop to call the manager’s manager until you get a nil result.