polymorphic-parent-resources
Installation
SKILL.md
Polymorphic Parent Resources
Overview
Apps accumulate child resources that hang off many different parents — comments, generated_reports, duplications, attachments. The naive approaches both scale badly:
- A namespaced controller per parent (
Estimates::CommentsController,Widgets::CommentsController,Accounts::CommentsController) — identical code, N copies, N sets of specs. - Non-RESTful actions bolted onto each parent controller (
EstimatesController#add_comment) — breaks REST and spreads comment logic across the app.
This pattern uses one route concern plus one controller to serve every parent. The parent's class name travels as a route default, and resource_for turns it back into the record.
When to Use
- A child resource belongs to two or more parent models (or will soon)
- About to duplicate a controller whose only difference is which parent it loads
- Consolidating existing per-parent controllers — see
references/retrofit.md
When not to use: a child with exactly one parent and no plans for more. A plain nested controller with Parent.find(params[:parent_id]) is clearer. Reach for this pattern at the second parent, not in anticipation of one.