In an Active Record Employee model, how do you declare a self-referential manager link and the reports that point back to it?
answer
- one employees table, manager_id column
- class_name: "Employee" on both sides
- foreign_key: :manager_id on has_many
- optional: true for the top
- inverse_of: since foreign_key: blocks guessing
basics
~10 sAdd a manager_id column to employees, then declare belongs_to :manager, class_name: "Employee", optional: true and has_many :reports, class_name: "Employee", foreign_key: :manager_id, inverse_of: :manager.
solid answer
~40 sA self-referential link is two ordinary associations on one model pointing at the same table. In a fleet company where drivers report to dispatchers, `employees` gets a `manager_id` column. `belongs_to :manager, class_name: "Employee", optional: true` reads it: `class_name:` is needed because no `Manager` class exists, and `optional: true` because belongs_to is required by default and the head of the depot has no manager. `has_many :reports, class_name: "Employee", foreign_key: :manager_id` goes the other way; with neither `foreign_key:` nor `inverse_of:` Rails would look for `employee_id`. Adding `inverse_of: :manager` matters because `foreign_key:` switches off automatic inverse detection, so `dispatcher.reports.first.manager` would otherwise query for a manager already in memory.
code
ruby · 16 linesclass AddManagerToEmployees < ActiveRecord::Migration[8.1]
def change
add_reference :employees, :manager, foreign_key: { to_table: :employees }
end
end
class Employee < ApplicationRecord
belongs_to :manager, class_name: "Employee", optional: true
has_many :reports, class_name: "Employee", foreign_key: :manager_id,
inverse_of: :manager, dependent: :nullify
end
dispatcher = Employee.create!(name: "Rosa")
driver = dispatcher.reports.create!(name: "Ana")
driver.manager == dispatcher # => true
dispatcher.manager # => nil, allowed by optional: truego deeper
Recall the two declarations: belongs_to :manager and has_many :reports, both with class_name: "Employee", and the manager_id column they share.
Explain each option: class_name: because the names match no class, foreign_key: because has_many would guess employee_id, optional: true, and inverse_of:.
Cover the production edges: deleting a manager with reports, preventing cycles, and why subtree queries need recursion rather than another association.
Decide when an org chart outgrows parent pointers and needs a dedicated tree storage pattern for reporting queries.
## The shape of a self-referential link A **self-referential association** links rows of one table to other rows of the same table. The classic case is an org chart: in a fleet company, drivers report to a dispatcher and dispatchers report to a depot manager, and all of them are rows in `employees`. The link is a single column, `manager_id`, that holds the id of another employee. Rails has no special macro for this. You declare two ordinary associations on the same model, and because their names do not match a class or the default foreign key, you spell those out. ## The declarations and why each option is there ```ruby class Employee < ApplicationRecord belongs_to :manager, class_name: "Employee", optional: true has_many :reports, class_name: "Employee", foreign_key: :manager_id, inverse_of: :manager end ``` - **`class_name: "Employee"`** on both: Rails derives the target class from the association name, so `:manager` would look for a `Manager` class and `:reports` for `Report`. - **`optional: true`** on `belongs_to`: in a new app `belongs_to` is required by default, so an employee with a nil manager fails validation with a "must exist" error. Someone sits at the top of every tree. - **`foreign_key: :manager_id`** on `has_many`: with no `foreign_key:` and no `inverse_of:`, a `has_many` derives its key from the owner's class name and would look for `employee_id`. The `belongs_to :manager` side derives `manager_id` from its own name. When `inverse_of: :manager` is declared, Rails 8.1 can also take the key from that `belongs_to`, so the explicit `foreign_key:` is belt and braces. - **`inverse_of: :manager`**: automatic inverse detection is skipped for associations that set `foreign_key:`, and would guess the name `:employee` anyway. Declaring it lets `dispatcher.reports.each { |r| r.manager }` reuse the loaded dispatcher instead of querying for it once per report. ## The column The migration adds the column with a foreign key to the same table: 1. `add_reference :employees, :manager, foreign_key: { to_table: :employees }` creates `manager_id`, an index, and a constraint pointing at `employees.id`. 2. The column stays nullable, which matches `optional: true` for the people at the top. ## Reading the link from both ends Once both associations exist, the column can be queried by association name instead of raw ids: - `Employee.where(manager: nil)` finds the people at the top of the chart. - `Employee.where(manager: dispatcher)` is the same set as `dispatcher.reports`. - `driver.update!(manager: other_dispatcher)` moves a driver by rewriting `manager_id`. - `dispatcher.reports.count` runs a `COUNT` on `employees` filtered by `manager_id`. Because both ends are `Employee` records, every employee answers both questions: a dispatcher has a manager and has reports, and a driver has a manager and an empty `reports` collection. ## What queries run | Call | SQL shape | |---|---| | `driver.manager` | `SELECT employees.* FROM employees WHERE employees.id = <manager_id> LIMIT 1` | | `dispatcher.reports` | `SELECT employees.* FROM employees WHERE employees.manager_id = <id>` | | `dispatcher.reports.create!(name: "Ana")` | an `INSERT` with `manager_id` set to the dispatcher's id | Each association goes one level. `dispatcher.reports` returns direct reports only; walking a whole subtree takes recursion, either in Ruby, one query per level, or in SQL with a recursive common table expression. How to store and query deep trees efficiently is a schema-design question rather than an association one. ## Traps - **Deleting a manager.** With the foreign key constraint in place, destroying a dispatcher who still has reports fails at the database. Decide what happens to the reports, for example with a `dependent:` option on `has_many :reports`. - **Cycles.** Nothing stops `a.manager = b` and `b.manager = a`. If the chart must be a tree, add a validation that rejects an employee as their own manager or ancestor. - **Names.** Pick association names that read well from both ends: `manager` and `reports`, or `supervisor` and `crew`. The column name follows the `belongs_to` side. - **Other self-links.** The same pattern links vehicles to a towing vehicle, or depots to a parent depot; a many-to-many self-link, such as employees covering for each other, goes through a join model instead.
- How would you load an employee's whole reporting subtree, not just direct reports?`reports` goes one level, so a subtree needs recursion: walk level by level in Ruby, which costs a query per level, or run a recursive common table expression in SQL. For deep, frequently read charts, a different storage pattern for the tree is the usual answer.
- What goes wrong if you leave optional: true off the belongs_to :manager?In a Rails app with current defaults, `belongs_to` is required, so saving an employee with no manager adds a "must exist" error and `save` returns false. The depot manager at the top of the chart could never be saved.
- A self-referential link needs polymorphic: true because both ends are the same model.
- has_many :reports, class_name: "Employee" with no other option reads manager_id.
- Rails detects the inverse of has_many :reports automatically, foreign_key: or not.
- dispatcher.reports returns every employee below the dispatcher, at all depths.